Deserialize JSON to c# object - c#

{"facet_counts":{
"facet_queries":{},
"facet_fields":{},
"facet_dates":{},
"facet_ranges":{
"createdat":{
"counts":[
"2015-05-17T00:00:00Z",155,
"2015-05-18T00:00:00Z",162,
"2015-05-19T00:00:00Z",200,
"2015-05-20T00:00:00Z",218,
"2015-05-21T00:00:00Z",181,
"2015-05-22T00:00:00Z",137],
"gap":"+1DAY",
"start":"2015-05-17T00:00:00Z",
"end":"2015-05-23T00:00:00Z"}}}}
I am trying to deserialize the above json into my object but the counts part is not getting deserialized. My object is
public class FacetCounts
{
public class Facet_Ranges
{
public class CreatedAt
{
public List<Counts> counts { get; set; }
public class Counts
{
public Dictionary<string, int> count { get; set; }
}
}
public CreatedAt createdat { get; set; }
}
public Facet_Ranges facet_ranges { get; set; }
}
I also tried removing the public Dictionary<string, int> count { get; set; } but still it fails.
My deserialize code is
objObject = JsonConvert.DeserializeObject<FacetCounts>(json);
Any help would be appreciated !!

public class FacetCounts
{
public class Facet_Ranges
{
public class CreatedAt
{
public List<string> counts
{
get
{
return Counts
.SelectMany(pair => new[]{pair.Key, pair.Value.ToString()})
.ToList();
}
set
{
var pairs = new Dictionary<string, int>();
for (var i = 0; i < value.Length / 2; ++i)
{
pairs[value[2*i]] = int.Parse(value[2*i+1]);
}
this.Counts = pairs;
}
}
[JsonIgnore]
public Dictionary<string, int> Counts {get;set;}
}
public CreatedAt createdat { get; set; }
}
public Facet_Ranges facet_ranges { get; set; }
}

Your JSon is invalid.
The error is the lack of braces around the complete JSon string {}
Here is a working JSon string:
{
"facet_counts": {
"facet_queries": {},
"facet_fields": {},
"facet_dates": {},
"facet_ranges": {
"createdat": {
"counts": [
"2015-05-17T00:00:00Z",
155,
"2015-05-18T00:00:00Z",
162,
"2015-05-19T00:00:00Z",
200,
"2015-05-20T00:00:00Z",
218,
"2015-05-21T00:00:00Z",
181,
"2015-05-22T00:00:00Z",
137
],
"gap": "+1DAY",
"start": "2015-05-17T00:00:00Z",
"end": "2015-05-23T00:00:00Z"
}
}
}
}
I used JSon Lint for validating your JSon, and fixed error by error.
I am not sure if your C# code is correct to Deserialize your JSon, so I would recommend you to use e.g. JSon2CSharp in order to create you JSon objects in C#. Then you can fix variable names, etc.

Surround each item in counts with {}
"facet_counts":{
"facet_queries":{},
"facet_fields":{},
"facet_dates":{},
"facet_ranges":{
"createdat":{
"counts":[
{"2015-05-17T00:00:00Z",155},
{"2015-05-18T00:00:00Z",162},
{"2015-05-19T00:00:00Z",200},
{"2015-05-20T00:00:00Z",218},
{"2015-05-21T00:00:00Z",181},
{"2015-05-22T00:00:00Z",137}],
"gap":"+1DAY",
"start":"2015-05-17T00:00:00Z",
"end":"2015-05-23T00:00:00Z"}}}

That isn't valid json - Your count objects need to be in {braces}.
FYI - You can also use json2csharp.com to auto-generate the c-sharp object to deserialize with, which would also highlight issues like this.

From JSON2CSHARP
public class Createdat
{
public List<object> counts { get; set; }
public string gap { get; set; }
public string start { get; set; }
public string end { get; set; }
}
This worked for me

Related

JArray to c# Object

I have this json string:
[
{
"id":"EORDERING_GRE017",
"name":"DELIMITER",
"value":"|"
},
{
"id":"EORDERING_GRE017",
"name":"ENABLED",
"value":"Y"
},
{
"id":"EORDERING_GRE017",
"name":"EXTERNALERRORRECIPIENT",
"value":"jaymie#moo.co.uk; matt#moo.co.uk"
},
{
"id":"EORDERING_GRE017",
"name":"FILETYPE",
"value":"delimited"
},
{
"id":"EORDERING_GRE017",
"name":"INTERNALERRORRECIPIENT",
"value":"jaymie#moo.co.uk; matt#moo.co.uk"
},
{
"id":"EORDERING_GRE017",
"name":"USESOWNBRANCHCODES",
"value":"True"
},
{
"id":"EORDERING_GRE017",
"name":"USESOWNSKUS",
"value":"True"
}
]
And I would like to turn that json into my class, which looks like this:
public class Settings
{
public bool Enabled { get; set; }
public string FileType { get; set; }
public string Delimiter { get; set; }
public string OrderFileSuffix { get; set; }
public string ResultFileSuffix { get; set; }
public bool UseOwnBranchCodes { get; set; }
public bool UseOwnProductCodes { get; set; }
public string InternalContacts { get; set; }
public string ExternalContacts { get; set; }
}
But I am unsure which is the best way to do this. Can someone give me a hand? :)
You could create a NameValue object:
public class NameValuePair
{
public string Name { get; set; }
public string Value { get; set; }
}
And deserialize the json array to List and convert it to Dictionary:
var dict = JsonConvert.DeserializeObject<List<NameValuePair>>(json).ToDictionary(x => x.Name, x => x.Value);
Then create a custom converter class with a method that accepts this dictionary and returns a Settings object:
public class SettingsConverter
{
public Settings Convert(IDictionary<string, string> data)
{
return new Settings
{
Enabled = data["ENABLED"].Equals("Y", StringComparison.Ordinal),
...
};
}
}
The JSON is an array of objects that would fit this class:
public class Setting
{
public string Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
So deserialize into that:
var settingList = JsonConvert.DeserializeObject<Setting[]>(jsonString);
But then you want to map specific settings to specific properties of that Settings class. You could do that by trying to find the particular setting for each property in the list of settings:
var settingsObject = new Settings
{
FileType = settingList.FirstOrDefault(s => s.Name == "FILETYPE")?.Value,
Delimiter = settingList.FirstOrDefault(s => s.Name == "DELIMITER")?.Value,
// ...
}
You'll have to manually map the properties. If you don't want that, you could write a custom serializer, but that'll quickly become a maintenance nightmare.
For those out there that may need some more help with the JSON Class Configuration, try: http://json2csharp.com/#
An excellent way of Auto Generating the Classes!
Or even easier, in VS, Goto:
Edit -> Paste Special -> Paste as JSON Classes

Deserializing Many Json Objects into List - C# [duplicate]

I have this JSON and I cannot figure out how to convert it to a List of objects in C#.
Here is the JSON:
{
"2": {
"sell_average": 239,
"buy_average": 238,
"overall_average": 240,
"id": 2
},
"6": {
"sell_average": 184434,
"buy_average": 182151,
"overall_average": 189000,
"id": 6
},
"8": {
"sell_average": 11201,
"buy_average": 1723,
"overall_average": 180,
"id": 8
}
}
And the code I've tried using:
public class ItemSummaryModel
{
public string Id { get; set; }
public ItemSummary ItemSummary { get; set; }
}
public class ItemSummary
{
public int Sell_Average { get; set; }
public int Buy_Average { get; set; }
public int Overall_Average { get; set; }
public int Id { get; set; }
}
List<ItemSummaryModel> models =
JsonConvert.DeserializeObject<List<ItemSummaryModel>>(jsonSummary);
to no avail. How can I deserialize this JSON into lists of these objects using Newtonsoft's JSON library (Json.Net)?
You can use
var dict = JsonConvert.DeserializeObject<Dictionary<int, ItemSummary>>(json);
var items = dict.Values.ToList(); //if you want a List<ItemSummary>;
public class ItemSummaryModel
{
[JsonProperty(PropertyName = "2")]
public ItemSummary Two { get; set; }
[JsonProperty(PropertyName = "6")]
public ItemSummary Six { get; set; }
[JsonProperty(PropertyName = "8")]
public ItemSummary Eight { get; set; }
}
var result = JsonConvert.DeserializeObject<ItemSummaryModel>(json);
This will technically work to get you a complex object, but I don't much like it. Having numbers for property names is going to be an issue. This being json for a single complex object will also be tricky. If it were instead a list, you could begin writing your own ContractResolver to handle mapping the number property name to an id field and the actual object to whatever property you wanted.

Read JSON Array that contains Arrays(?) C#

I apologize in advance for the poor explanation of my problem.
I'm trying to read a JSON array that contains data.
Here's how the JSON looks:
{
"playerstats": {
"steamID": "76561198071680006",
"gameName": "GameName",
"achievements": [
{
"apiname": "AchievementName1",
"achieved": 0, <--- Data that I want to read
"unlocktime": 0
},
{
"apiname": "AchievementName2",
"achieved": 0, <--- Data that I want to read
"unlocktime": 0
},
{
"apiname": "AchievementName2",
"achieved": 1, <--- Data that I want to read
"unlocktime": 1477847680
}
]
,
"success": true
}
}
I'm trying to look at Newtonsoft.Json and how to use that yet I'm at a complete loss as to how to use this. Any help would be appreciated.
You can try JsonConvert.DeserializeObject to read json data.
Having
public class Rootobject
{
public Playerstats playerstats { get; set; }
}
public class Playerstats
{
public string steamID { get; set; }
public string gameName { get; set; }
public Achievement[] achievements { get; set; }
public bool success { get; set; }
}
public class Achievement
{
public string apiname { get; set; }
public int achieved { get; set; }
public int unlocktime { get; set; }
}
You can try this:
var filePath = path to your file;
var jsonData = System.IO.File.ReadAllText(filePath);
Rootobject objectValue =
Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonData);
Note: you should remove <--- Data that I want to read parts from your json data because currently it is not a valid json format.
You may access to your desired properties like this
objectValue.playerstats.achievements[0].achieved //0
objectValue.playerstats.achievements[1].achieved //0
objectValue.playerstats.achievements[2].achieved //1

Parse complex JSON: multiple loops vs. classes

I have a Json of type :
{
"JobProcessors": [
{
"JobName": "ArchivalJob",
"IsEnabled": true,
"Batching": {
"BatchSize": 0,
"DegreeOfParallelism": -1
},
"Settings": {
"ArchivalJobCollectionPageSize": 50
}
},
{
"JobName": "AuditLogJob",
"IsEnabled": false,
"Batching": {
"BatchSize": 10,
"DegreeOfParallelism": -1
},
"Settings": {}
}
],
"ScheduledJobs": [
{
"JobName": "RemoteStartClientCommandJob",
"PrimaryAction": {
"ConnectionString": "#JobProcessorsIntegrationSBConnectionStringValue#",
"Settings": {
"LeadTimeInSeconds": "600",
"MaxSrsJobCount": 25
}
},
"ErrorAction": {
"ConnectionString": "#PairedJobProcessorIntegrationSBConnectionStringValue#",
"EntityPath": "remotestartqueue",
"Settings": {
"LeadTimeInSeconds": "600",
"MaxSrsJobCount": 25
}
}
}
]
}
I want to check the "IsEnabled" property for all "JobName" for which come under "JobProcessors" category.
In C# what i Have used till now is :
dynamic parsedJson = JsonConvert.DeserializeObject(reader.GetString(1));
foreach (var item in parsedJson)
{
foreach (var smallitem in item)
{
foreach (var tag in smallitem)
{
if(tag.IsEnabled.toString()=="true"){
Console.WriteLine("true");
}
}
}
}
This is giving me correct result except the fact that it also iterates for "ScheduledJobs" . But the main issue is :
Is this the right or most efficient way to do this ? If possible suggest some better method .
One that i know of is using classes , but i may not know the json structure beforehand. Also the json is very huge so making classes can be cumbersome !!
Given that you are already doing JObject.Parse(jsonstring); to parse your JSON string, you can use SelectTokens() with a JSONPath query to find all "JobName" objects under "JobProcessors":
// I want to check the "IsEnabled" property for all "JobName" for which come under "JobProcessors"
foreach (var job in root.SelectTokens("..JobProcessors[?(#.JobName)]"))
{
var isEnabled = (bool?)job["IsEnabled"];
Debug.WriteLine(string.Format("Job {0}: IsEnabled={1}", job["JobName"], isEnabled));
}
Notes:
.. is the recursive descent operator: it recursively descends the JToken hierarchy returning each item, subsequently to be matched against the remaining parts of the query string.
JobProcessors returns values of properties of that name.
[?(#.JobName)] returns array items (of JobProcessors in this case) that are objects with a JobName property.
(bool?) casts the value of "IsEnabled" to a boolean or null if missing.
And the output of this is:
Job ArchivalJob: IsEnabled=True
Job AuditLogJob: IsEnabled=False
As in your code snippet we are using two foreach it may take time for large object. So we can do the same thing in a single foreach or if you have some specific node to fetch or search we can use linq, and for this first we need to convert our json object into c# object. For converting Json object to C# you can use this site "http://json2csharp.com/" then we can Deserialize Json object into c#.
It will be something like this
string jsonString = "your Json Object as string";
var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
foreach (JobProcessor obj in jsonObject.JobProcessors)
{
string JobName = obj.JobName;
bool value=obj.IsEnabled;
}
And I also converted given Json in c# object if the Json object is same you can directly use these classes.
public class Batching
{
public int BatchSize { get; set; }
public int DegreeOfParallelism { get; set; }
}
public class Settings
{
public int ArchivalJobCollectionPageSize { get; set; }
}
public class JobProcessor
{
public string JobName { get; set; }
public bool IsEnabled { get; set; }
public Batching Batching { get; set; }
public Settings Settings { get; set; }
}
public class Settings2
{
public string LeadTimeInSeconds { get; set; }
public int MaxSrsJobCount { get; set; }
}
public class PrimaryAction
{
public string ConnectionString { get; set; }
public Settings2 Settings { get; set; }
}
public class Settings3
{
public string LeadTimeInSeconds { get; set; }
public int MaxSrsJobCount { get; set; }
}
public class ErrorAction
{
public string ConnectionString { get; set; }
public string EntityPath { get; set; }
public Settings3 Settings { get; set; }
}
public class ScheduledJob
{
public string JobName { get; set; }
public PrimaryAction PrimaryAction { get; set; }
public ErrorAction ErrorAction { get; set; }
}
public class RootObject
{
public List<JobProcessor> JobProcessors { get; set; }
public List<ScheduledJob> ScheduledJobs { get; set; }
}
Hope this will help.
Thank you

Deserialize Json like { List : { [ ... ], [ ... ] } }

It's my first work with Json.
I've already installed Json.Net in my Visual Studio project and used to deserialize some simple string like this:
{
"A":"1",
"B":"2",
"C":"3"
}
With this code:
JToken token = JObject.Parse("{ "A":"1","B":"2","C":"3"}";
string aValue = token.SelectToken("A");
string aValue = token.SelectToken("B");
string aValue = token.SelectToken("C");
But I don't know how to do with a Json like this:
{
"LIST":[
{
"A":"value1",
"B":"value1",
"C":"value1"
}
{
"A":"value2",
"B":"value2",
"C":"value2"
}
{
"A":"value3",
"B":"value3",
"C":"value3"
}
],
"D":"value4",
"E":"value5",
"F":"value6"
}
How can get all elements of type and the other variable like D, E and F?
Thank you
The easiest way would be to create objects and deserialize into those:
public class Parent
{
public Child[] LIST { get; set; }
public string D { get; set; }
public string E { get; set; }
public string F { get; set; }
}
public class Child
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
Once you have your classes defined, deserializing your JSON is as easy as:
var p = JsonConvert.DeserializeObject<Parent>(json);
#Justin's answer is good and will work well. However, if you want to continue using the LINQ-to-JSON API style as you are doing now, here is how you can get all the info:
JToken token = JToken.Parse(jsonString);
foreach (JToken t in token["LIST"])
{
Console.WriteLine(t["A"]);
Console.WriteLine(t["B"]);
Console.WriteLine(t["C"]);
}
Console.WriteLine(token["D"]);
Console.WriteLine(token["E"]);
Console.WriteLine(token["F"]);

Categories

Resources