I hate some trouble sorting the data I recieve from a webresponse.
Right now they come in "random", and I haven't been able to sort it at all.
Right now the partial class looks like this:
namespace computers{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
using J = Newtonsoft.Json.JsonPropertyAttribute;
public partial class GettingStarted
{
[J("devices")] public Device[] Devices { get; set; }
}
public partial class Device
{
[J("device_id")] public string DeviceId { get; set; }
[J("assigned_to")] public bool AssignedTo { get; set; }
[J("alias")] public string Alias { get; set; }
[J("description")] public string Description { get; set; }
[J("last_seen")] public string LastSeen { get; set; }
[J("remotecontrol_id")] public string RemotecontrolId { get; set; }
[J("groupid")] public string Groupid { get; set; }
[J("online_state")] public string OnlineState { get; set; }
[J("supported_features")] public string SupportedFeatures { get; set; }
}
public partial class GettingStarted
{
public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
As said before, the data comes in random and all my attempts at sorting them result in either a crash or does nothing.
Thanks in advance!
You can use lambda expressions to achieve this
Add using System.Linq directive
After you pupulate your 'Devices' array, use this to sort it:
Devices = Devices.OrderBy(x=>x.Alias).ToArray()
Related
How can I build a Model class to deserialize a json like this:-
{"query":{"apikey":"65320-2d8b-11eb-864","continent":"Africa"},"data":{"0":{"country_id":1,"name":"Africa","country_code":null,"continent":"Africa"},"9":{"country_id":10,"name":"Algeria","country_code":"dz","continent":"Africa"},"11":{"country_id":12,"name":"Angola","country_code":"ao","continent":"Africa"},"23":{"country_id":24,"name":"Botswana","country_code":"bw","continent":"Africa"},"27":{"country_id":28,"name":"Cameroon","country_code":"cm","continent":"Africa"},"32":{"country_id":33,"name":"Congo","country_code":"cg","continent":"Africa"},"39":{"country_id":40,"name":"Egypt","country_code":"eg","continent":"Africa"},"48":{"country_id":49,"name":"Ghana","country_code":"gh","continent":"Africa"},"62":{"country_id":63,"name":"Ivory Coast","country_code":"ci","continent":"Africa"},"67":{"country_id":68,"name":"Kenya","country_code":"ke","continent":"Africa"},"80":{"country_id":81,"name":"Morocco","country_code":"ma","continent":"Africa"},"85":{"country_id":86,"name":"Nigeria","country_code":"ng","continent":"Africa"},"102":{"country_id":103,"name":"Rwanda","country_code":"rw","continent":"Africa"},"106":{"country_id":107,"name":"Senegal","country_code":"sn","continent":"Africa"},"111":{"country_id":112,"name":"South Africa","country_code":"za","continent":"Africa"},"115":{"country_id":116,"name":"Tanzania","country_code":"tz","continent":"Africa"},"118":{"country_id":119,"name":"Tunisia","country_code":"tn","continent":"Africa"},"120":{"country_id":121,"name":"Uganda","country_code":"ug","continent":"Africa"},"129":{"country_id":130,"name":"Zambia","country_code":"zm","continent":"Africa"},"130":{"country_id":131,"name":"Zimbabwe","country_code":"zw","continent":"Africa"}}}
The problem is in the numbers like "0", "9", "11" etc! How can I convert these numbers to one property in the model class?
If you implement the data item as a Dictionary on your model, these numbers would be the keys of this Dictionary.
public class Model
{
[JsonProperty("query")]
public Query query {get; set; }
[JsonProperty("data")]
public Dictionary<string, Country> Data { get; set; }
}
public class Country
{
[JsonProperty("country_id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country_code")]
public string Code { get; set; }
[JsonProperty("continent")]
public string Continent { get; set; }
}
public class Query
{
[JsonProperty("apikey")]
public string ApiKey { get; set; }
[JsonProperty("continent")]
public string Continent { get; set; }
}
You can treat these numbers as keys of an dictionary. So may convert them like this:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var testJson = "{\"data\":{\"11\": \"test11\"}}";
var deserialized = (TestClass) JsonConvert.DeserializeObject(testJson, typeof(TestClass));
Console.WriteLine(deserialized.Data[11]);
}
}
public class TestClass
{
public Dictionary<int, string> Data {get;set;}
}
(to test see this dotnetfiddle example)
Obviously only possible if no number appears twice or more.
I have a model like below:
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
PrimaryBuyerInputModel like below:
public class PrimaryBuyerInformationInputModel
{
[Required]
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
[Required]
public string BuyerLastName { get; set; }
}
and when I am submitting my form then I am getting JSON like below:
{
"PrimaryBuyerInformation.BuyerFirstName": "Sunil",
"PrimaryBuyerInformation.BuyerMiddleInitial": "",
"PrimaryBuyerInformation.BuyerLastName": "Choudhary",
"TermsCondition": "true"
}
When I am trying to deserialize this json the TermsCondition property successfully done, but the property of PrimaryBuyerInformation is not mapped.
var myObject = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Any idea how to do that ?
Kindly take a cue from the code below, i tested it and you should be able to get your value as request. This solves the issue of you trying to access the property you have mapped in a dot property name format.
Instead your object should be nested in a curly brace showing that the other property belongs to PrimaryBuyerInformationInputModel which is another object entirely.
Best Regards,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = #"{'PrimaryBuyerInformation': {'buyerFirstName': 'Sunil','buyerMiddleInitial': '','buyerLastName': 'Choudhary'},'termsCondition': false}";
var obj = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Console.WriteLine(obj.PrimaryBuyerInformation.BuyerFirstName);
}
}
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
public class PrimaryBuyerInformationInputModel
{
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
public string BuyerLastName { get; set; }
}
JSON
{
"SoftHoldIDs": 444,
"AppliedUsages": [
{
"SoftHoldID": 444,
"UsageYearID": 223232,
"DaysApplied": 0,
"PointsApplied": 1
}
],
"Guests": [
1,
2
]
}
In the above JSON SoftholdIDs is integer and AppliedUsages is class array property in C# Model
Issue is --How we can map JSON to class property.
Class code
public class ReservationDraftRequestDto
{
public int SoftHoldIDs { get; set; }
public int[] Guests { get; set; }
public AppliedUsage[] AppliedUsages { get; set; }
}
public class AppliedUsage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
Tried below code for mapping
ReservationDraftRequestDto reservationDto = null;
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data.ToString());
You need to change
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
to
string data = await reservationDraftRequestDto.Content.ReadAsStringAsync();
this will read your response as string
then do
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data);
this work
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string json = #"{""SoftHoldIDs"": 444,""AppliedUsages"": [ {""SoftHoldID"": 444,""UsageYearID"": 223232,""DaysApplied"": 0,""PointsApplied"": 1}],""Guests"": [ 1, 2]}";
Rootobject reservationDto = JsonConvert.DeserializeObject<Rootobject>(json.ToString());
Debug.WriteLine(reservationDto.SoftHoldIDs);
foreach (var guest in reservationDto.Guests)
{
Debug.WriteLine(guest);
}
}
}
public class Rootobject
{
public int SoftHoldIDs { get; set; }
public Appliedusage[] AppliedUsages { get; set; }
public int[] Guests { get; set; }
}
public class Appliedusage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
}
First create class copying json as classwith visualstudio.
Next you have double quote in json respons so deal with it.
Json.NET: Deserilization with Double Quotes
Hi I have a simple nested json and am trying to parse it with Javascriptserializer(). I created a class with properties and one more class for another nested data. But am not able to access full properties
I have tried the below code
This works well and below is my class where am saving this content
when i do
Please try below code.
I have tried with Newtonsoft.Json
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var jsonData ="{\"Command\":\"te\",\"Data\":{\"Image\":\"/6D/ogARAP8\",\"Imagetype\":\"FLS\",\"Imageformat\":\"bmp\",\"MissingFingers\":[\"FLIF\",\"FLMF\"]}}";
var jsonRootObject = JsonConvert.DeserializeObject<RootObject>(jsonData);
Console.WriteLine(jsonRootObject.Data.MissingFingers[0]);
Console.WriteLine(jsonRootObject.Data.Imagetype);
Console.WriteLine(jsonRootObject.Data.Image);
}
public class Data
{
public string Image { get; set; }
public string Imagetype { get; set; }
public string Imageformat { get; set; }
public List<string> MissingFingers { get; set; }
}
public class RootObject
{
public string Command { get; set; }
public Data Data { get; set; }
}
}
Like demo here
I have a json object and I am trying to convert it to my c# object. Here is my JSON:
{"GuvenlikNoktaArray": {"GuvenlikNoktası": [{"Id": 1,"GuvenlikNoktası1":"SANTIYE","KartNo":"000001889174217","Sira": 1},{"Id": 2,"GuvenlikNoktası1":"INSAAT","KartNo":"000000803567858","Sira": 2},{"Id": 3,"GuvenlikNoktası1":"ÇALISMA","KartNo":"000003417926233","Sira": 3},{"Id": 4,"GuvenlikNoktası1":"GÜVENLIK","KartNo":"000001888909897","Sira": 4}]}}
And my c# class:
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
And last, my convert try:
public void AddIstasyon(string json_string)
{
GuvenlikNoktası result = new JavaScriptSerializer().Deserialize<GuvenlikNoktası>(json_string);
}
I don't get any errors but when I debuged, I see that all attributes inside 'result' are null. It seems like an empty object. How can I get a correct 'GuvenlikNoktası' object ? (Btw I am pretty sure I am getting the json object correctly).
If you must keep this JSON structure as-is you may use JObject to navigate inside your JSON properties until you reach your target objects to deserizlize. Please can you try the code below;
PS: This code uses Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SO_39847703
{
class Program
{
static void Main(string[] args)
{
string json = "{\"GuvenlikNoktaArray\": {\"GuvenlikNoktası\": [{\"Id\": 1,\"GuvenlikNoktası1\":\"SANTIYE\",\"KartNo\":\"000001889174217\",\"Sira\": 1},{\"Id\": 2,\"GuvenlikNoktası1\":\"INSAAT\",\"KartNo\":\"000000803567858\",\"Sira\": 2},{\"Id\": 3,\"GuvenlikNoktası1\":\"ÇALISMA\",\"KartNo\":\"000003417926233\",\"Sira\": 3},{\"Id\": 4,\"GuvenlikNoktası1\":\"GÜVENLIK\",\"KartNo\":\"000001888909897\",\"Sira\": 4}]}}";
AddIstasyon(json);
}
public static void AddIstasyon(string json_string)
{
dynamic jsonObject = JObject.Parse(json_string);
string jsonToDeserializeStrongType = jsonObject["GuvenlikNoktaArray"]["GuvenlikNoktası"].ToString();
List<GuvenlikNoktası> result = JsonConvert.DeserializeObject<List<GuvenlikNoktası>>(jsonToDeserializeStrongType); ;
}
}
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
public class GüvenlikNoktasıOlay
{
}
public class PanikButonuAlarmlari
{
}
}
Hope this helps
Your JSON data and your class definition do not fit together. Therefore the default values (NULL) are provided by the serializer.
In order to deserialize the given JSON data you need a class structure like:
public class Root
{
public LevelOne GuvenlikNoktaArray {get; set;}
}
public class LevelOne {
public IEnumerable<GuvenlikNoktası> GuvenlikNoktası {get; set;}
}
You can use this class.
public class GuvenlikNoktası
{
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public int Sira { get; set; }
}
public class GuvenlikNoktaArray
{
public IList<GuvenlikNoktası> GuvenlikNoktası { get; set; }
}
public class Example
{
public GuvenlikNoktaArray GuvenlikNoktaArray { get; set; }
}
You can use this link For your referencehttp://jsonutils.com/.