I am using Newtonsoft package in C#.
I am trying to display all the items listed in a nested JSON array. I am having difficulty displaying the Name Jennifer Jones
This is what the JSON String Looks Like
"responseDetails": {
"pageoffset": 0,
"size": 950,
},
"data": [
{
"id": 473145,
"name": "Class of 2000",
"doc_prog":
{
"responseDetails":
{
"pageoffset": 0,
"size": 1,
},
"data": [
{
"name": "Jennifer Jones"
}
]
},
This is what my class looks like
public respDetails responseDetails { get; set; }
public class respDetails
{
public int pageoffset { get; set; }
public string size { get; set; }
}
public List<datas> data { get; set; } // Top level class attribute
public class datas
{
public int id { get; set; }
public string name__v { get; set; }
public Programs doc_prog { get; set; }
public class Programs
{
public respDetails responseDetails { get; set; }
public class respDetails
{
public int pageoffset { get; set; }
public int size { get; set; }
}
public List<datasprogram> data { get; set; } // Top level class attribute
public class datasprogram
{
public string name { get; set; }
}
}
}
This is how I set up the for loop to list all the items in the array
var jRelated = JsonConvert.DeserializeObject<JDocsClass>(strRelated);
foreach (var num in jRelated.data)
{
Console.WriteLine(" Page Offset " + num.doc_prog.responseDetails.pageoffset.ToString() + " " + num.doc_prog.data.ToString() );
}
This is the Program Output
Page Offset 0 System.Collections.Generic.List`1[storeAPI.JCorrespondenceDocsClass+datas+Programs+datasprogram]
So Instead of displaying "Jennifer Jones", I am displaying "System.Collections.Generic.List...."
I appreciate any help pointing me in the right direction
num.doc_prog.data.ToString()
Here what you are trying to print is list!
num.doc_prog.data[0].name
This will give you the desired result if there is atleast one element in the list (which is there in your example json), if there are multiple names then to display them you need to loop thru num.doc_prog.data
foreach(datasprogram data in num.doc_prog.data)
{
string name = data.name;
}
Related
I have the following JSON string
{
"data": [
{
"symbol": "1COV.GE",
"exposure": "0",
"makerExposure": "-2028",
"takerExposure": "2028",
"makerPnl": "447.6688",
"takerPnl": "-447.6688",
"makerPositions": [
{
"name": "IB_001",
"position": "-2028",
"vwap": "47.41",
"pnl": "447.6688"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "2028",
"vwap": "47.41",
"pnl": "-447.6688"
}
]
},
{
"symbol": "A",
"exposure": "0",
"makerExposure": "-10",
"takerExposure": "10",
"makerPnl": "-4.6",
"takerPnl": "4.6",
"makerPositions": [
{
"name": "IB_002",
"position": "-10",
"vwap": "136.78",
"pnl": "-4.6"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "10",
"vwap": "136.78",
"pnl": "4.6"
}
],
"total": 2
}
}
And my goal is to serialize it into a List of object from the NODE "Data":
I have the classes that map the data node fields:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public OZPositions makerPositions { get; set; }
public OZPositions takerPositions { get; set; }
}
Do you have any ideas how I can convert the node "data" to list of "ExPositions" objects, eg. List
I've did this but so far it throws an error
var positions = JsonSerializer.Deserialize<ExPositions>(json_string);
There is an error in your json - it's missing a closing ] for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data node of the json which should contain a list (or array) of ExPositions. The makerPositions and takerPositions should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2 property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data class above (if it belongs there).
Online demo
Try with:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public Positions makerPositions { get; set; }
public Positions takerPositions { get; set; }
}
public class YourResult{
public ExPositions data { get; set; }
public int total { get; set; }
}
And then call:
var positions = JsonSerializer.Deserialize<YourResult>(json_string);
As haldo mentioned, there is a typo in your JSON. To quickly parse and validate your JSON data, you can use any online JSON parsers to validate your JSON data. I usually use the chrome extension JSON Viewer Pro.
Also, in the link that haldo provided to the .NET Fiddle for the demo, there is a trailing comma in JSON data which JSON deserializers might not ignore.
Here is the link to the edited demo that haldo provided.
Edited Demo
I've been searching and trying to get this to work for hours and i'm completely out of ideas. I have JSON text that i'm trying to read and can't see it get it to work. Here is the JSON text.
[ {
"first_aired": "2018-03-03T01:00:00.000Z",
"episode": {
"season": 3,
"number": 13,
"title": "Warning Shot",
"ids": {
"trakt": 2814272,
"tvdb": 6445735,
"imdb": "tt7462514",
"tmdb": 1429184,
"tvrage": 0
}
},
"show": {
"title": "Blindspot",
"year": 2015,
"ids": {
"trakt": 98980,
"slug": "blindspot",
"tvdb": 295647,
"imdb": "tt4474344",
"tmdb": 62710,
"tvrage": 44628
}
} }, {
"first_aired": "2018-03-03T01:00:00.000Z",
"episode": {
"season": 2,
"number": 16,
"title": "Hammock + Balcony",
"ids": {
"trakt": 2874663,
"tvdb": 6535389,
"imdb": "tt7820776",
"tmdb": 1428050,
"tvrage": 0
}
},
"show": {
"title": "MacGyver",
"year": 2016,
"ids": {
"trakt": 107792,
"slug": "macgyver-2016",
"tvdb": 311902,
"imdb": "tt1399045",
"tmdb": 67133,
"tvrage": {}
}
} } ]
I'm trying to get the "episode -> season" and "episode - > number"
This is the code ive been working with and also a fiddle below.
string json = "[{\"first_aired\":\"2018-03-03T01:00:00.000Z\",\"episode\":{\"season\":3,\"number\":13,\"title\":\"Warning Shot\",\"ids\":{\"trakt\":2814272,\"tvdb\":6445735,\"imdb\":\"tt7462514\",\"tmdb\":1429184,\"tvrage\":0}},\"show\":{\"title\":\"Blindspot\",\"year\":2015,\"ids\":{\"trakt\":98980,\"slug\":\"blindspot\",\"tvdb\":295647,\"imdb\":\"tt4474344\",\"tmdb\":62710,\"tvrage\":44628}}},{\"first_aired\":\"2018-03-03T01:00:00.000Z\",\"episode\":{\"season\":2,\"number\":16,\"title\":\"Hammock + Balcony\",\"ids\":{\"trakt\":2874663,\"tvdb\":6535389,\"imdb\":\"tt7820776\",\"tmdb\":1428050,\"tvrage\":0}},\"show\":{\"title\":\"MacGyver\",\"year\":2016,\"ids\":{\"trakt\":107792,\"slug\":\"macgyver-2016\",\"tvdb\":311902,\"imdb\":\"tt1399045\",\"tmdb\":67133,\"tvrage\":null}}}]";
JArray obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(json);
foreach (var result in obj)
{
foreach (JObject tvshow in result["episode"])
{
string season_num = (string)tvshow["season"];
string episode_num = (string)tvshow["number"];
Console.WriteLine(season_num + " - " + episode_num );
}
}
https://dotnetfiddle.net/speUyL
Thank's for any help anyone can give me!
You actually have nested objects, so you will need to first extract the episode object and then from the episode you can access it's properties which are number and season etc:
foreach (var result in obj)
{
var episode = result["episode"];
Console.WriteLine(episode["season"]);
Console.WriteLine(episode["number"]);
}
This prints the result you are trying to do. Following is the updated fiddle demo:
https://dotnetfiddle.net/WN545C
A easy approach is to have DTO c# classes for your json and then Deserialize the json result in to List<T>. The classes for your json would be :
public class Ids
{
public int trakt { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Episode
{
public int season { get; set; }
public int number { get; set; }
public string title { get; set; }
public Ids ids { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public object tvrage { get; set; }
}
public class Show
{
public string title { get; set; }
public int year { get; set; }
public Ids2 ids { get; set; }
}
public class Season
{
public DateTime first_aired { get; set; }
public Episode episode { get; set; }
public Show show { get; set; }
}
An easy way to get the classes generated is by using Json2CSharp.com or either using the Visual Studio feature which can paste JSON as C# classes using Paste Special.
and now you can deserialize and access each season data more better way:
var seasons = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Season>>(json);
foreach (var season in seasons)
{
Console.WriteLine(season.episode.title);
Console.WriteLine(season.first_aired);
Console.WriteLine(season.episode.season);
Console.WriteLine(season.episode.number);
}
You can play with the demo for that here:
https://dotnetfiddle.net/hukLQI
So I'm calling the LinkedIn API to get the profile data and it retrieves a JSON.
{
"firstName": "Cristian Viorel",
"headline": ".NET Developer",
"location": {
"country": {"code": "dk"},
"name": "Northern Region, Denmark"
},
"pictureUrls": {
"_total": 1,
"values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
}
}
I can use student.firstname, student.headline. How can I get the name of the location, or the value of the pictureUrl ?
Something like student.location.name or student.pictureUrls.values ?
Pretty easy with Json.Net. You first define your model:
public class Country
{
public string code { get; set; }
}
public class Location
{
public Country country { get; set; }
public string name { get; set; }
}
public class PictureUrls
{
public int _total { get; set; }
public List<string> values { get; set; }
}
public class JsonResult
{
public string firstName { get; set; }
public string headline { get; set; }
public Location location { get; set; }
public PictureUrls pictureUrls { get; set; }
}
Then you simply parse your Json data:
string json = #"{
'firstName': 'Cristian Viorel',
'headline': '.NET Developer',
'location': {
'country': {'code': 'dk'},
'name': 'Northern Region, Denmark'
},
'pictureUrls': {
'_total': 1,
'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
}
}";
JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);
Console.WriteLine(result.location.name);
foreach (var pictureUrl in result.pictureUrls.values)
Console.WriteLine(pictureUrl);
For the name yes, but for picture you need a for loop or if you just want the first item student.pictureUrls.values[0] (values seems to be an array).
i'm trying to program a Windows Runtime Component in C# in Visual Studio 2012 for Windows 8.
I have some issues by using Json.NET to deserialize a JSON like this:
{
"header": {
"id": 0,
"code": 0,
"hits": 10
},
"body": {
"datalist": [
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
}
]
}
}
My intention is to get a top-level Dictionary out of this and to interpret every value as a string. For this example you would get a dictionary with two keys (header and body) and the matching values as strings. After this you could go down the tree.
A function like this
Dictionary<string, string> jsonDict =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
would be nice, but this one only accept string-values.
Do anybody knows how to ignore the types or get it on another way?
Furthermore to get out of the body-value "{"datalist": [ { "name": "", ....}]}" a list of dictionaries.
Thanks in advance!
I would use this site and deserialize as
var myObj =JsonConvert.DeserializeObject<RootObject>(json);
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
public class Body
{
public List<Datalist> datalist { get; set; }
}
public class RootObject
{
public Header header { get; set; }
public Body body { get; set; }
}
You can also use dynamic keyword without declaring any classes
dynamic myObj =JsonConvert.DeserializeObject(json);
var age = myObj.body.datalist[1].age;
And since JObject implements IDictionary<> this is also possible
var jsonDict = JObject.Parse(json);
var age = jsonDict["body"]["datalist"][1]["age"];
If you're having a problem defining your classes, a nice feature in VS 2012 allows you to generate classes to hold your JSON/XML data using the Paste Special command under Edit. For instance, your JSON created this class:
public class Rootobject
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Body
{
public Datalist[] datalist { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
...which you could then deserialize your request into the type of RootObject, e.g.
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Need to parse JSON like this:
{
"Status": "Success",
"Data": {
"Folders": [
{
"Folder ID": 1,
"Name": "12"
},
{
"Folder ID": 2,
"Name": "3"
}
]
}
}
Doing as:
public class getFoldersDataFolders
{
public int FolderID { get; set; }
public string Name { get; set; }
}
public class getFoldersDataAnswer
{
public List<getFoldersDataFolders> Folders { get; set; }
}
public class getFoldersAnswer
{
public string Status { get; set; }
public getFoldersDataAnswer Data { get; set; }
}
...
var gfA = JsonConvert.DeserializeObject<WAAPIJSONClasses.getFoldersAnswer>( answer );
for ( var i = 0; i < gfA.Data.Folders.Count; i++ )
{
folders[ gfA.Data.Folders[ i ].Name ] = gfA.Data.Folders[ i ].FolderID;
}
in gfA.Data.Folders[ i ].FolderID i have 0.
I think the problem is that the name of the field "Folder ID" consists of two words (separated by spaces).
So, how to get the value of the field if the field name contains multiple words (separated by spaces)?
Thanks for answer.
Try to:
public class getFoldersDataFolders
{
[JsonProperty(PropertyName = "Folder ID")]
public int FolderID { get; set; }
public string Name { get; set; }
}