deserializing dynamic named JSON attributes to a C# class - c#

{
"Documents": {
"c97bba6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "name",
"sys": {
"c67bfa6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "sys name"
},
"a67bfa6f-c8ab-4453-91f8-f663f478910c": {
"id": " a67bfa6f-c8ab-4453-91f8-f663f478910c",
"name": "sys name"
}
}
},
"f97bba6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "OZL - B - MECH - AC - Fan Coil Units",
"sys": {}
}
}
}
I've got JSON data in the form above and am having trouble deserializing this into a C# class. The trouble I'm having is that the GUID is used to define the object that the Documents object has rather than the documents object having a list of documents.
I've tried to create a documents object that has a list of object in it and deserialise into this using Newtonsoft. I've also tried a dictionary of string, object in the documents object. None of these work.
Any input or ideas would be most appreciated.
Edit: the biggest issue I'm having is the nesting of Dictionary<GUID, object>. Newtonsoft won't map to the dictionary within the first object. Here's what I have:
public class Documents {
public dictionary<Guid, System> data { get; set; }
}
public class System {
public Guid Id { get; set;}
public string Name { get; set; }
public dictionary<guid, someOtherobject> otherData { get; set;}
}

Based on your JSON, the class structure you need is this:
public class RootObject
{
public Dictionary<Guid, Document> Documents { get; set; }
}
public class Document
{
public Guid Id { get; set; }
public string Name { get; set; }
public Dictionary<Guid, Sys> Sys { get; set; }
}
public class Sys
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Then deserialize into the RootObject class like this:
var root = JsonConvert.DeserializeObject<RootObject>(json);
Here is a working demo: https://dotnetfiddle.net/Uycomw

Related

How to deserialize root JSON dynamic property name in C#? [duplicate]

I've got the following json document:
{
"name": "bert",
"Bikes": {
"Bike1": {
"value": 1000,
"type": "Trek"
},
"Bike2": {
"value": 2000,
"type": "Canyon"
}
}
}
With potentially other bikes like Bike3...BikeN. I want to deserialize to C# objects. Problem is that in the deserialization step the bikes data is completely lost, resulting in a null Bikes collection.
Code to reproduce:
[Test]
public void FirstCityJsonParsingTest()
{
var file = #"./testdata/test.json";
var json = File.ReadAllText(file);
var res = JsonConvert.DeserializeObject<Person>(json);
Assert.IsTrue(res.Name == "bert");
// next line is failing, because res.Bikes is null...
Assert.IsTrue(res.Bikes.Count == 2);
}
public class Bike
{
public string Id { get; set; }
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Name { get; set; }
public List<Bike> Bikes { get; set; }
}
To fix this problem a change in the used model is necessary. But what change is needed here to fill the bikes data correctly?
Note: Changing the input document is not an option (as it's a spec)
Your code structure is not reflecting your json. Common approach to deserializing json with dynamic property names is to use Dictionary<string, ...> (supported both by Json.NET and System.Text.Json). Try the following:
public class Bike
{
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Bike> Bikes { get; set; }
}
Person.Bikes should be changed to Dictionary<string, Bike> (also Bike.Id property is not needed) cause Bikes json element is not an array but object.

Dynamic json property deserialize

I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me
I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?
{
"objects": {
"UserRequest::567": {
"code": 0,
"message": "created",
"class": "UserRequest",
"key": "567",
"fields": {
"ref": "R-000567",
"org_id": "4"
}
}
}
}
The question is what are the best practices to read through this kind of a json string?
Thank you
To Deserialize this using Newtonsoft.Json, here are the classes:
public class CreateRequest
{
public long code { get;set; }
public string message { get; set; }
[JsonProperty("class")]
public string class1 { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
[JsonProperty("ref")]
public string refe { get; set; }
public string org_id { get; set; }
}
public class Root
{
public Dictionary<string, CreateRequest> objects { get; set; }
//The 'string' key in the dictionary is the 'UserRequest::567'
}
Then to Deserialize use:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;

Deserialize json object with dynamic items in C#

I've got the following json document:
{
"name": "bert",
"Bikes": {
"Bike1": {
"value": 1000,
"type": "Trek"
},
"Bike2": {
"value": 2000,
"type": "Canyon"
}
}
}
With potentially other bikes like Bike3...BikeN. I want to deserialize to C# objects. Problem is that in the deserialization step the bikes data is completely lost, resulting in a null Bikes collection.
Code to reproduce:
[Test]
public void FirstCityJsonParsingTest()
{
var file = #"./testdata/test.json";
var json = File.ReadAllText(file);
var res = JsonConvert.DeserializeObject<Person>(json);
Assert.IsTrue(res.Name == "bert");
// next line is failing, because res.Bikes is null...
Assert.IsTrue(res.Bikes.Count == 2);
}
public class Bike
{
public string Id { get; set; }
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Name { get; set; }
public List<Bike> Bikes { get; set; }
}
To fix this problem a change in the used model is necessary. But what change is needed here to fill the bikes data correctly?
Note: Changing the input document is not an option (as it's a spec)
Your code structure is not reflecting your json. Common approach to deserializing json with dynamic property names is to use Dictionary<string, ...> (supported both by Json.NET and System.Text.Json). Try the following:
public class Bike
{
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Bike> Bikes { get; set; }
}
Person.Bikes should be changed to Dictionary<string, Bike> (also Bike.Id property is not needed) cause Bikes json element is not an array but object.

read multiple Json data from webservice

i have a web service that returns a Json string.
my problem is that i have difficulties to read it
i tried with:
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
var myobj = jsSerializer.Deserialize<List<CinfoRichiesta>>(jsonData);
but how can i get values from "students" and "locations"?
with javascript i used :" var j = jQuery.parseJSON(msg.d);" but i think with c# code would be different
this is an example of string:
{"Questions":{
"id":"2",
"BOOK":"3",
"students":{
"class":"3",
"theme","43"
},
"locations":{
"h":"0",
"L":"3"
}
}
}
First off, your JSON isn't valid so thats the first problem you have. You can verify this at http://jsonlint.com/ for example.
i have currently fixed this in the following way:
{
"Questions": {
"id": "2",
"BOOK": "3",
"students": {
"class": "3",
"theme": "na",
"43": "na"
},
"locations": {
"h": "0",
"L": "3"
}
}
}
Second your class should be correct, with the current JSON this should look something like this
public class Rootobject
{
public Questions Questions { get; set; }
}
public class Questions
{
public string id { get; set; }
public string BOOK { get; set; }
public Students students { get; set; }
public Locations locations { get; set; }
}
public class Students
{
public string _class { get; set; }
public string theme { get; set; }
public string _43 { get; set; }
}
public class Locations
{
public string h { get; set; }
public string L { get; set; }
}
After this you can deserialize it like this
var myobj = jsSerializer.Deserialize<List<Rootobject>>(jsonData);
And then you can get the information like this
myobj.Questions.students._class
You're deserializing to a collection of type CinfoRichiesta, which should hold a property value for students and locations.
Assuming that your JSON is correctly formatted and your class definition is suitable for the response (I recommend double checking it by pasting the entire response string into json2csharp.com)
Once that's all validated, you should be able to see the students and locations collections internally like so:
foreach(Question q in myobj)
{
Console.WriteLine(q.students.class)
}
which should give you the result of 3.
edit
I think your main question is why you're unable to access the properties of students and locations. Make sure Students is its own class as such:
public class Students
{
public int class { get; set; }
public int theme { get; set; }
}
and your locations class should be:
public class Locations
{
public int h { get; set; }
public int l { get; set; }
}
You should then have a questions class that instaniates both students and locations, as such:
public class Questions
{
public int id { get; set; }
public int book { get; set; }
public Student students { get; set; }
public Locations locations { get; set; }
}
When working with JSON deserialization, it's important that your object property names (ie class) match the response string in terms of case. So If you wrote it as public int Theme, it won't directly map.
Slightly annoying in terms of coding standards, but hey ho :-)

JSON deserialize variable number of properties

I have a JSON class structure like this from a third party API (only the problem part shown):
"template": {
"name": "MovieTemplate",
"ruleName": "Movie Template",
"zones": {
"Products": {
"type": "Record",
"name": "Products",
"content": "www.imagescloudsite.com/blahblah.gif"
"records": [ … ]
},
"URL": {
"type":"DVD",
"name":"Bundle"
"content": "www.imagescloudsite.com/blahblah.gif"
}
}
}
The "zones" property can contain many properties "Products","URL","Superman","Descartes",etc...
But, I do not know which ones and how many will be there, because these are added by our content guys in a special control panel. Newtonsoft Deserializer complains because I have a model like this and it clearly does not capture the zone name like 'Products' and 'URL':
public class Zone
{
public string Type { get; set; }
public string Name { get; set; }
public string Content { get; set; }
}
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public List<Zone> Zones { get; set; }
}
Any ideas on how I can capture the zone names using NewtonSoft?
Thanks.
Turn your Zone property to a dictionary since you don't know the keys in before hand, but do know their content structure.
Like so
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public Dictionary<string,Zone> Zones { get; set; }
}
What if you changed the Template class to the following:
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public Dictionary<string, Zone> Zones { get; set; }
}
You could then access the name via the key of the entry.
Use of dynamic would be a good bet
dynamic d = Newtonsoft.Json.Linq.JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Categories