Deserialise Dynamic JSON string with Hierarchical data using JSON.NET - c#

Ive a JSON like this
{
"id": 1,
"name": "user1",
"hasChildren": true,
"parentID": 0,
"children": [
{
"id": 2,
"name": "user2",
"paretnID": 1,
"hasChildren": true,
"children": [
{
"id": 3,
"name": "user3",
"parentID": 2,
"hasChildren": false,
"children": [
]
},
{
"id": 4,
"name": "user4",
"parentID": 2,
"hasChildren": false,
"children": [
]
}
]
},
{
"id": 5,
"name": "user5",
"paretnID": 1,
"hasChildren": true,
"children": [
{
"id": 6,
"name": "user6",
"parentID": 5,
"hasChildren": false,
"children": [
]
},
{
"id": 7,
"name": "user7",
"parentID": 5,
"hasChildren": false,
"children": [
]
}
]
},
{
"id": 8,
"name": "user8",
"paretnID": 1,
"hasChildren": true,
"children": [
{
"id": 9,
"name": "user9",
"parentID": 8,
"hasChildren": false,
"children": [
]
},
{
"id": 10,
"name": "user10",
"parentID": 8,
"hasChildren": true,
"children": [
{
"id": 11,
"name": "user11",
"parentID": 10,
"hasChildren": false,
"children": [
]
},
{
"id": 12,
"name": "user12",
"parentID": 10,
"hasChildren": false,
"children": [
]
}
]
}
]
}
]
}
Here as you can see its maintaining a hierarchy in each level in the children node. What my scenario is to convert this dynamic JSON as datatable rows
For deserilising this is how I tried
dynamic myJSON=jObject.parse(JSONstring);
but when I try myJSON.id its triggering an error like id not exists
What my plant is if children array has some elements, call another function to get its members and add to the datatable. But how can I get these fields from the dyanmic json string.

You can use like this
public class Child2
{
public int id { get; set; }
public string name { get; set; }
public int parentID { get; set; }
public bool hasChildren { get; set; }
public List<object> children { get; set; }
}
public class Child
{
public int id { get; set; }
public string name { get; set; }
public int paretnID { get; set; }
public bool hasChildren { get; set; }
public List<Child2> children { get; set; }
}
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public bool hasChildren { get; set; }
public int parentID { get; set; }
public List<Child> children { get; set; }
}
then Deserialize
var data=JsonConvert.DeserializeObject<RootObject>(JSONstring);
then you can access data.id
You need to add reference Newtonsoft.json

Related

Display Consumed API on web Page

So ive connected a n external API and I want to display it on the page, but im not getting any luck.
I'm using RestSharp so I cant just collect the infromation as such:
string results = response.Content.ReadAsStringAsync().Result;
Also because i'm using RestSharp, collecting the returned api information with:
string results = response.Content;
this causes the program to crash because it cannot be inserted into the data table. From what im seeing it needs to be deserialized, but im not sure how thats done in RestSharp.
EDIT 1:
This is my model class based on the API results
using Newtonsoft.Json;
namespace NBA_API_TEST.Models
{
public class NBAModel
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("league")]
public string League { get; set; }
[JsonProperty("season")]
public long Season { get; set; }
[JsonProperty("date")]
public Date Date { get; set; }
[JsonProperty("stage")]
public long Stage { get; set; }
[JsonProperty("status")]
public Status Status { get; set; }
[JsonProperty("periods")]
public Periods Periods { get; set; }
[JsonProperty("arena")]
public Arena Arena { get; set; }
[JsonProperty("teams")]
public Teams Teams { get; set; }
[JsonProperty("scores")]
public Scores Scores { get; set; }
[JsonProperty("officials")]
public object[] Officials { get; set; }
[JsonProperty("timesTied")]
public object TimesTied { get; set; }
[JsonProperty("leadChanges")]
public object LeadChanges { get; set; }
[JsonProperty("nugget")]
public object Nugget { get; set; }
}
public partial class Arena
{
[JsonProperty("name")]
public object Name { get; set; }
[JsonProperty("city")]
public object City { get; set; }
[JsonProperty("state")]
public object State { get; set; }
[JsonProperty("country")]
public object Country { get; set; }
}
public partial class Date
{
[JsonProperty("start")]
public DateTimeOffset Start { get; set; }
[JsonProperty("end")]
public object End { get; set; }
[JsonProperty("duration")]
public object Duration { get; set; }
}
public partial class Periods
{
[JsonProperty("current")]
public long Current { get; set; }
[JsonProperty("total")]
public long Total { get; set; }
[JsonProperty("endOfPeriod")]
public object EndOfPeriod { get; set; }
}
public partial class Scores
{
[JsonProperty("visitors")]
public ScoresHome Visitors { get; set; }
[JsonProperty("home")]
public ScoresHome Home { get; set; }
}
public partial class ScoresHome
{
[JsonProperty("win")]
public object Win { get; set; }
[JsonProperty("loss")]
public object Loss { get; set; }
[JsonProperty("series")]
public Series Series { get; set; }
[JsonProperty("linescore")]
public object[] Linescore { get; set; }
[JsonProperty("points")]
public long Points { get; set; }
}
public partial class Series
{
[JsonProperty("win")]
public object Win { get; set; }
[JsonProperty("loss")]
public object Loss { get; set; }
}
public partial class Status
{
[JsonProperty("clock")]
public object Clock { get; set; }
[JsonProperty("halftime")]
public object Halftime { get; set; }
[JsonProperty("short")]
public long Short { get; set; }
[JsonProperty("long")]
public string Long { get; set; }
}
public partial class Teams
{
[JsonProperty("visitors")]
public TeamsHome Visitors { get; set; }
[JsonProperty("home")]
public TeamsHome Home { get; set; }
}
public partial class TeamsHome
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("logo")]
public Uri Logo { get; set; }
}
}
from the API call 5 results should be returned.
So I have these set up
IList<NBAModel> GameModel = new List<NBAModel>();
GameModel = JsonConvert.DeserializeObject<List<NBAModel>>(results);
But that causes this error to be returned:
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[NBA_API_TEST.Models.NBAModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
EDIT 2
Update with my JSON
{
"get": "games/",
"parameters": {
"season": "2021",
"h2h": "1-2"
},
"errors": [],
"results": 5,
"response": [
{
"id": 9484,
"league": "vegas",
"season": 2021,
"date": {
"start": "2021-08-08T20:00:00.000Z",
"end": null,
"duration": null
},
"stage": 2,
"status": {
"clock": null,
"halftime": null,
"short": 3,
"long": "Finished"
},
"periods": {
"current": 4,
"total": 4,
"endOfPeriod": null
},
"arena": {
"name": null,
"city": null,
"state": null,
"country": null
},
"teams": {
"visitors": {
"id": 2,
"name": "Boston Celtics",
"nickname": "Celtics",
"code": "BOS",
"logo": "https://upload.wikimedia.org/wikipedia/fr/thumb/6/65/Celtics_de_Boston_logo.svg/1024px-Celtics_de_Boston_logo.svg.png"
},
"home": {
"id": 1,
"name": "Atlanta Hawks",
"nickname": "Hawks",
"code": "ATL",
"logo": "https://upload.wikimedia.org/wikipedia/fr/e/ee/Hawks_2016.png"
}
},
"scores": {
"visitors": {
"win": null,
"loss": null,
"series": {
"win": null,
"loss": null
},
"linescore": [],
"points": 85
},
"home": {
"win": null,
"loss": null,
"series": {
"win": null,
"loss": null
},
"linescore": [],
"points": 83
}
},
"officials": [],
"timesTied": null,
"leadChanges": null,
"nugget": null
},
{
"id": 9780,
"league": "standard",
"season": 2021,
"date": {
"start": "2021-11-18T00:30:00.000Z",
"end": "2021-11-18T02:43:00.000Z",
"duration": "2:03"
},
"stage": 2,
"status": {
"clock": null,
"halftime": false,
"short": 3,
"long": "Finished"
},
"periods": {
"current": 4,
"total": 4,
"endOfPeriod": false
},
"arena": {
"name": "State Farm Arena",
"city": "Atlanta",
"state": "GA",
"country": "USA"
},
"teams": {
"visitors": {
"id": 2,
"name": "Boston Celtics",
"nickname": "Celtics",
"code": "BOS",
"logo": "https://upload.wikimedia.org/wikipedia/fr/thumb/6/65/Celtics_de_Boston_logo.svg/1024px-Celtics_de_Boston_logo.svg.png"
},
"home": {
"id": 1,
"name": "Atlanta Hawks",
"nickname": "Hawks",
"code": "ATL",
"logo": "https://upload.wikimedia.org/wikipedia/fr/e/ee/Hawks_2016.png"
}
},
"scores": {
"visitors": {
"win": 7,
"loss": 8,
"series": {
"win": 0,
"loss": 1
},
"linescore": [
"29",
"20",
"28",
"22"
],
"points": 99
},
"home": {
"win": 7,
"loss": 9,
"series": {
"win": 1,
"loss": 0
},
"linescore": [
"30",
"28",
"33",
"19"
],
"points": 110
}
},
"officials": [
"Leon Wood",
"Zach Zarba",
"Suyash Mehta"
],
"timesTied": null,
"leadChanges": null,
"nugget": null
},
{
"id": 10302,
"league": "standard",
"season": 2021,
"date": {
"start": "2022-01-29T00:30:00.000Z",
"end": "2022-01-29T02:54:00.000Z",
"duration": "2:13"
},
"stage": 2,
"status": {
"clock": null,
"halftime": false,
"short": 3,
"long": "Finished"
},
"periods": {
"current": 4,
"total": 4,
"endOfPeriod": false
},
"arena": {
"name": "State Farm Arena",
"city": "Atlanta",
"state": "GA",
"country": "USA"
},
"teams": {
"visitors": {
"id": 2,
"name": "Boston Celtics",
"nickname": "Celtics",
"code": "BOS",
"logo": "https://upload.wikimedia.org/wikipedia/fr/thumb/6/65/Celtics_de_Boston_logo.svg/1024px-Celtics_de_Boston_logo.svg.png"
},
"home": {
"id": 1,
"name": "Atlanta Hawks",
"nickname": "Hawks",
"code": "ATL",
"logo": "https://upload.wikimedia.org/wikipedia/fr/e/ee/Hawks_2016.png"
}
},
"scores": {
"visitors": {
"win": 25,
"loss": 25,
"series": {
"win": 0,
"loss": 2
},
"linescore": [
"20",
"27",
"30",
"15"
],
"points": 92
},
"home": {
"win": 23,
"loss": 25,
"series": {
"win": 2,
"loss": 0
},
"linescore": [
"32",
"30",
"18",
"28"
],
"points": 108
}
},
"officials": [
"Scott Wall",
"Tom Washington",
"Josh Tiven"
],
"timesTied": 5,
"leadChanges": 9,
"nugget": null
},
{
"id": 10421,
"league": "standard",
"season": 2021,
"date": {
"start": "2022-02-13T19:00:00.000Z",
"end": "2022-02-13T21:27:00.000Z",
"duration": "2:15"
},
"stage": 2,
"status": {
"clock": null,
"halftime": false,
"short": 3,
"long": "Finished"
},
"periods": {
"current": 4,
"total": 4,
"endOfPeriod": false
},
"arena": {
"name": "TD Garden",
"city": "Boston",
"state": "MA",
"country": "USA"
},
"teams": {
"visitors": {
"id": 1,
"name": "Atlanta Hawks",
"nickname": "Hawks",
"code": "ATL",
"logo": "https://upload.wikimedia.org/wikipedia/fr/e/ee/Hawks_2016.png"
},
"home": {
"id": 2,
"name": "Boston Celtics",
"nickname": "Celtics",
"code": "BOS",
"logo": "https://upload.wikimedia.org/wikipedia/fr/thumb/6/65/Celtics_de_Boston_logo.svg/1024px-Celtics_de_Boston_logo.svg.png"
}
},
"scores": {
"visitors": {
"win": 26,
"loss": 30,
"series": {
"win": 2,
"loss": 1
},
"linescore": [
"28",
"27",
"23",
"17"
],
"points": 95
},
"home": {
"win": 33,
"loss": 25,
"series": {
"win": 1,
"loss": 2
},
"linescore": [
"17",
"28",
"42",
"18"
],
"points": 105
}
},
"officials": [
"Kane Fitzgerald",
"Karl Lane",
"Brandon Adair"
],
"timesTied": 2,
"leadChanges": 1,
"nugget": null
},
{
"id": 10492,
"league": "standard",
"season": 2021,
"date": {
"start": "2022-03-02T00:30:00.000Z",
"end": "2022-03-02T03:09:00.000Z",
"duration": "2:20"
},
"stage": 2,
"status": {
"clock": null,
"halftime": false,
"short": 3,
"long": "Finished"
},
"periods": {
"current": 4,
"total": 4,
"endOfPeriod": false
},
"arena": {
"name": "TD Garden",
"city": "Boston",
"state": "MA",
"country": "USA"
},
"teams": {
"visitors": {
"id": 1,
"name": "Atlanta Hawks",
"nickname": "Hawks",
"code": "ATL",
"logo": "https://upload.wikimedia.org/wikipedia/fr/e/ee/Hawks_2016.png"
},
"home": {
"id": 2,
"name": "Boston Celtics",
"nickname": "Celtics",
"code": "BOS",
"logo": "https://upload.wikimedia.org/wikipedia/fr/thumb/6/65/Celtics_de_Boston_logo.svg/1024px-Celtics_de_Boston_logo.svg.png"
}
},
"scores": {
"visitors": {
"win": 29,
"loss": 32,
"series": {
"win": 2,
"loss": 2
},
"linescore": [
"28",
"37",
"13",
"20"
],
"points": 98
},
"home": {
"win": 37,
"loss": 27,
"series": {
"win": 2,
"loss": 2
},
"linescore": [
"19",
"32",
"31",
"25"
],
"points": 107
}
},
"officials": [
"Eric Lewis",
"Curtis Blair",
"Scott Twardoski"
],
"timesTied": 7,
"leadChanges": 6,
"nugget": null
}
]
}
for your classes you can try this, but you will not have a root level data in this cases
List<NBAModel> nbaModels=JObject.Parse(json)["response"].ToObject<List<NBAModel>>();
public partial class TeamsHome
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public Name Name { get; set; }
[JsonProperty("nickname")]
public Nickname Nickname { get; set; }
[JsonProperty("code")]
public Code Code { get; set; }
[JsonProperty("logo")]
public Uri Logo { get; set; }
}
public enum Code { Atl, Bos };
public enum Name {
[EnumMember(Value = "Atlanta Hawks")]
AtlantaHawks,
[EnumMember(Value = "Boston Celtics")]
BostonCeltics };
public enum Nickname { Celtics, Hawks };
if you want the whole data you need to add this classes
Data data = JsonConvert.DeserializeObject<Data>(json);
public partial class Data
{
[JsonProperty("get")]
public string Get { get; set; }
[JsonProperty("parameters")]
public Parameters Parameters { get; set; }
[JsonProperty("errors")]
public List<object> Errors { get; set; }
[JsonProperty("results")]
public long Results { get; set; }
[JsonProperty("response")]
public List<NBAModel> Response { get; set; }
}
public partial class Parameters
{
[JsonProperty("season")]
public long Season { get; set; }
[JsonProperty("h2h")]
public string H2H { get; set; }
}

Problems deserializing Newtonsoft JSON in c# returning null

I'm trying to deserialize a json in c# with Newtonsoft, but when i try to print the elements, it returns null.
The json is the following:
{
"data": [
{
"ufs": [
{
"delivery": [
{
"grade": "100",
"name": "P01",
"id": 10,
"status": "submitted"
},
{
"name": "P02",
"id": 11,
"status": "new"
}
],
"name": "UF1",
"id": "18"
},
{
"delivery": [
{
"name": "P03",
"id": 12,
"status": "new"
},
{
"name": "P04",
"id": 13,
"status": "new"
}
],
"name": "UF2",
"id": "19"
}
],
"name": "M1",
"id": "5"
},
{
"ufs": [
{
"delivery": [
{
"name": "P01",
"id": 6,
"status": "submitted"
},
{
"name": "P02",
"id": 7,
"status": "new"
}
],
"name": "UF1",
"id": "23"
},
{
"delivery": [
{
"name": "P03",
"id": 8,
"status": "new"
},
{
"name": "P04",
"id": 9,
"status": "new"
}
],
"name": "UF2",
"id": "24"
}
],
"name": "M2",
"id": "6"
}
]
}
So, having this JSON, i went to this site to generate the classes i would need, that are the following ones:
public class Delivery
{
public string grade { get; set; }
public string name { get; set; }
public int id { get; set; }
public string status { get; set; }
}
public class Uf
{
public List<Delivery> delivery { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Root
{
public List<Uf> ufs { get; set; }
public string name { get; set; }
public string id { get; set; }
}
So finally, when i deserialize the JSON with this line
List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(json);
And try to print
foreach (Root item in myDeserializedClass)
{
Console.WriteLine(item.ufs.Count);
}
It says "Root.ufs.get returned null."
Any clue of where im mistaking? Thanks for the help!
Grettings from Spain!
You class structure would be like this
public class Delivery
{
public string grade { get; set; }
public string name { get; set; }
public int id { get; set; }
public string status { get; set; }
}
public class Uf
{
public List<Delivery> delivery { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Data
{
public List<Uf> ufs { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Root
{
public List<Data> data { get; set; }
}
When you needed to deserialize the Json you will do like this
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);
Here is the json that I used
string json = #"{'data': [
{
'ufs': [
{
'delivery': [
{
'grade': '100',
'name': 'P01',
'id': 10,
'status': 'submitted'
},
{
'name': 'P02',
'id': 11,
'status': 'new'
}
],
'name': 'UF1',
'id': '18'
},
{
'delivery': [
{
'name': 'P03',
'id': 12,
'status': 'new'
},
{
'name': 'P04',
'id': 13,
'status': 'new'
}
],
'name': 'UF2',
'id': '19'
}
],
'name': 'M1',
'id': '5'
},
{
'ufs': [
{
'delivery': [
{
'name': 'P01',
'id': 6,
'status': 'submitted'
},
{
'name': 'P02',
'id': 7,
'status': 'new'
}
],
'name': 'UF1',
'id': '23'
},
{
'delivery': [
{
'name': 'P03',
'id': 8,
'status': 'new'
},
{
'name': 'P04',
'id': 9,
'status': 'new'
}
],
'name': 'UF2',
'id': '24'
}
],
'name': 'M2',
'id': '6'
}
]
}";

I'm not able to convert IRestresponse to a object. What am i missing?

I hope someone can help me out here, because I'm pretty stuck ;)
I do not understand the error I'm getting:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'OdosTest.OdosRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Isn't my json respone (see in the bottom) okay?
I'm trying to deserialize my IRestResponse to a object, but with no luck. The classes should be finde, or where am I wrong?
Here is my code:
using System;
using RestSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace OdosTest
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://triscan.odosolutions.com/api/v1/streams");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic HIDDEN");
IRestResponse response = client.Execute(request);
var odosRecord = JsonConvert.DeserializeObject<OdosRecord>(response.Content);
//Console.WriteLine(response.Content);
}
}
public class OdosRecord
{
public int version { get; set; }
public string id { get; set; }
public int loggerImei { get; set; }
public string vin { get; set; }
public DateTime startTime { get; set; }
public Signal[] signals { get; set; }
}
public class Signal
{
public string source { get; set; }
public string name { get; set; }
public string displayName { get; set; }
public string number { get; set; }
public string unit { get; set; }
public bool isNumericComplement { get; set; }
public Value[] values { get; set; }
}
public class Value
{
public DateTime timestamp { get; set; }
public string value { get; set; }
}
}
Here is the response I get:
[
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}
]
Your json contains a List<OdosRecord>, so this should solve the issue:
var odosRecord = JsonConvert.DeserializeObject<List<OdosRecord>>(response.Content);
otherwise you cloud change your json to this (if you are able to change the contract):
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}

Using ASP.NET Core 3, how do I make the json response not serialize a complex type?

I have this model:
public class Product
{
public Product()
{
this.Supplier = new Supplier();
}
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int SupplierId { get; set; }
public ProductStatus Status { get; set; }
public Supplier Supplier { get; set; }
}
and another model:
public class Supplier
{
public Supplier()
{
this.Products = new List<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public ICollection<Product> Products { get; set; }
}
Whenever I try to send json response using the product model, I get this kind of result:
{
"id": 1,
"name": "HP-ENVY 15",
"price": 800,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 1,
"name": "HP",
"address": "Mckinley",
"products": []
}
}
And when trying to send a response using Supplier model:
{
"id": 1,
"name": "HP",
"address": "Mckinley",
"products": [
{
"id": 1,
"name": "HP-ENVY 15",
"price": 800,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 12,
"name": "HP-PAVILION 14",
"price": 550,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 13,
"name": "HP-ENVY 17",
"price": 1200.7,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 14,
"name": "Printer xxx-2020",
"price": 300.5,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 15,
"name": "Compaq Presario",
"price": 500.8,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
}
]
}
Both responses tries to serialize the complext object inside them, is it possible to:
1.) When sending the json response for the Product model, It would only display Products and its Supplier only(the products property of that supplier would not be inlcluded)
2.) When sending the json response for the Supplier model, it would only display the Supplier and its products only(the supplier property for each product would not be inlcuded)
Are there json options that I need to configure on my middleware in order to achieve this? or should I create DTOs/classes where the Supplier complex object being referenced inside the Product model has no property of its product and vice-versa for the Supplier model(it has no products property).
Note: I'm aware that it's best to use viewmodel/dtos for json response, but in my example let's just say that both Product and Model are not domain classes but rather viewmodels, as my main problem is how do I prevent json from preventing serializing the object property.
JSON.net has the MaxDepth property for deserealizing up to a certain point.
Beware though that this will help you up to a point. It will not identify same object cyclic dependency, it will just stop at the second level of deserialization.
For the opposite thing (serialization) you can use json.net limit maxdepth when serializing to extend the JsonTextWriter

Json.Net deserialize object give me empty object

I am trying to de-serialize this json string:
{"PatientData":[
{
"device": {
"serial": "M01106798",
"manufacturer": "Nipro",
"model": "TrueResult",
"first_value_at": "2010-07-17T22:39:00",
"last_value_at": "2010-09-30T11:18:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": []
},
{
"device": {
"serial": "59-50889-10",
"manufacturer": "Animas",
"model": "IR1200",
"first_value_at": "2014-02-07T11:46:00",
"last_value_at": "2014-03-27T10:38:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": [
{
"type": "insulin_bolus",
"created_at": "2014-02-07T23:42:00",
"unit": "U",
"total_value": 0.9,
"spike_value": 0.9,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T00:01:00",
"value": 0.175,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T05:01:00",
"value": 0.225,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T07:42:00",
"unit": "U",
"total_value": 2.6,
"duration": 1800,
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T09:38:00",
"unit": "U",
"total_value": 0.3,
"spike_value": 0.3,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "glucose",
"created_at": "2014-03-27T12:55:18",
"value": 33.167,
"unit": "mmol/l",
"flags": []
}
]
}
]}
by using classes generated from json2csharp like this
public class ObjPatientData
{
public class Device
{
public string serial { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string first_value_at { get; set; }
public string last_value_at { get; set; }
public string supports_glucose { get; set; }
public string supports_cgm { get; set; }
public string supports_insulin { get; set; }
public string supports_carb { get; set; }
}
public class PatientData
{
public Device device { get; set; }
public List<object> data { get; set; }
}
public class RootObject
{
public List<PatientData> PatientData { get; set; }
}
}
and calling it like this:
LPatientData = new List<ObjPatientData.RootObject>();
LPatientData = JsonConvert.DeserializeObject<List<ObjPatientData.RootObject>>(Json);
but I get a list of empty objects; any help will be appreciated.
Thanks!
please note that
Based on the above classes, I solved the issue by returning a list of "PatientData" objects rather than a list of "RootObjects" and using a Jarray.Parse(Json) in this way:
ObjPatientData.RootObject Root = new ObjPatientData.RootObject();
var jArray = JArray.Parse(Json);
Root.PatientData = jArray.ToObject<List<ObjPatientData.PatientData>>();
I think following the code will work.
string json = "{\"PatientData\":[{\"device\": {\"serial\": \"M01106798\",\"manufacturer\": \"Nipro\",\"model\": \"TrueResult\",\"first_value_at\": \"2010-07-17T22:39:00\",\"last_value_at\": \"2010-09-30T11:18:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": []},{\"device\": {\"serial\": \"59-50889-10\",\"manufacturer\": \"Animas\",\"model\": \"IR1200\",\"first_value_at\": \"2014-02-07T11:46:00\",\"last_value_at\": \"2014-03-27T10:38:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": [ {\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-07T23:42:00\",\"unit\": \"U\",\"total_value\": 0.9,\"spike_value\": 0.9,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T00:01:00\",\"value\": 0.175,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T05:01:00\",\"value\": 0.225,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T07:42:00\",\"unit\": \"U\",\"total_value\": 2.6,\"duration\": 1800,\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T09:38:00\",\"unit\": \"U\",\"total_value\": 0.3,\"spike_value\": 0.3,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]}, {\"type\": \"glucose\",\"created_at\": \"2014-03-27T12:55:18\",\"value\": 33.167,\"unit\": \"mmol/l\",\"flags\": []}]}]}";
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
RootObject rootObject = javaScriptSerializer.Deserialize<RootObject>(json);

Categories

Resources