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; }
}
Related
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;
}
I received this format of JSON string from some API.
{
"onlineRequest":{
"MobileNumber":"75484568",
"ProductNo":"100",
"JsonFile":{
"dropdown":[
{
"#para-id":"2572",
"#new-code":"",
"#text":"This is first dropdown",
"option":[
{
"#text":"Option 1",
"#value":"0"
}
]
},
{
"#para-id":"2584",
"#new-code":"",
"#text":"This is second dropdown",
"option":[
{
"#text":"Excellent",
"#value":"2"
}
]
},
{
"#para-id":"2575",
"#new-code":"",
"#text":"This is third dropdown",
"option":[
{
"#text":"Not Available",
"#value":"1"
}
]
}
]
}
}
}
In order to this JSON string, I need to bind the values to
JSON. each parameter ID has separate #value. which is dynamical. value of the #value can be 0,1,2,3,4
When #para-id = 2572,
if #value = 0, I need to pass the value to #new-code = 50,
if #value = 1, I need to pass the value to #new-code = 60,
if #value = 2, I need to pass the value to #new-code = 70
When #para-id = 2584,
if #value = 0, I need to pass the value to #new-code = 10,
if #value = 1, I need to pass the value to #new-code = 20,
if #value = 2, I need to pass the value to #new-code = 30,
When #para-id = 2575,
if #value = 0, I need to pass the value to #new-code = "A",
if #value = 1, I need to pass the value to #new-code = "B"
Expected Output :
"dropdown":[
{
"#para-id":"2572",
"#new-code":"50",
"#text":"This is first dropdown",
"option":[
{
"#text":"Option 1",
"#value":"0"
}
]
},
{
"#para-id":"2584",
"#new-code":"30",
"#text":"This is second dropdown",
"option":[
{
"#text":"Excellent",
"#value":"2"
}
]
},
{
"#para-id":"2575",
"#new-code":"B",
"#text":"This is third dropdown",
"option":[
{
"#text":"Not Available",
"#value":"1"
}
]
}
]
How can I do this using C#. please help me to solve this.
Updated:
in order to JSON, I created a model class. but the problem is when using #text,#value and #para-id.I know I can't create fields like this
public class Option
{
public string #text { get; set; }
public string #value { get; set; }
}
public class Dropdown
{
public string #para-id { get; set; }
public string #new-code { get; set; }
public string #text { get; set; }
public List<Option> option { get; set; }
}
public class JsonFile
{
public List<Dropdown> dropdown { get; set; }
}
public class OnlineRequest
{
public string MobileNumber { get; set; }
public string ProductNo { get; set; }
public JsonFile JsonFile { get; set; }
}
public class RootObject
{
public OnlineRequest onlineRequest { get; set; }
}
You can deserialize that JSON using this... It will first deserialize, project the Dropdown element and reserialize it to the JSON format
void Main()
{
string testJson = #"{""onlineRequest"":{""MobileNumber"":""75484568"",""ProductNo"":""100"",""JsonFile"":{""dropdown"":[{""#para-id"":""2572"",""#new-code"":"""",""#text"":""This is first dropdown"",""option"":[{""#text"":""Option 1"",""#value"":""0""}]},{""#para-id"":""2584"",""#new-code"":"""",""#text"":""This is second dropdown"",""option"":[{""#text"":""Excellent"",""#value"":""2""}]},{""#para-id"":""2575"",""#new-code"":"""",""#text"":""This is third dropdown"",""option"":[{""#text"":""Not Available"",""#value"":""1""}]}]}}}";
Response response = JsonConvert.DeserializeObject<Response>(testJson);
var dropdowns = response.OnlineRequest.JsonFile;
string json = JsonConvert.SerializeObject(dropdowns, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class Option
{
[JsonProperty("#text")]
public string Text { get; set; }
[JsonProperty("#value")]
public string Value { get; set; }
}
public class Dropdown
{
[JsonProperty("#para-id")]
public string ParaId { get; set; }
[JsonProperty("#new-code")]
public string NewCode { get; set; }
[JsonProperty("#text")]
public string Text { get; set; }
[JsonProperty("option")]
public IList<Option> Option { get; set; }
}
public class JsonFile
{
[JsonProperty("dropdown")]
public IList<Dropdown> Dropdown { get; set; }
}
public class OnlineRequest
{
[JsonProperty("MobileNumber")]
public string MobileNumber { get; set; }
[JsonProperty("ProductNo")]
public string ProductNo { get; set; }
[JsonProperty("JsonFile")]
public JsonFile JsonFile { get; set; }
}
public class Response
{
[JsonProperty("onlineRequest")]
public OnlineRequest OnlineRequest { get; set; }
}
Output looks like this
{
"dropdown": [
{
"#para-id": "2572",
"#new-code": "",
"#text": "This is first dropdown",
"option": [
{
"#text": "Option 1",
"#value": "0"
}
]
},
{
"#para-id": "2584",
"#new-code": "",
"#text": "This is second dropdown",
"option": [
{
"#text": "Excellent",
"#value": "2"
}
]
},
{
"#para-id": "2575",
"#new-code": "",
"#text": "This is third dropdown",
"option": [
{
"#text": "Not Available",
"#value": "1"
}
]
}
]
}
EDIT: in response to comment, change the NewCode property to this
void Main()
{
string testJson = #"{""onlineRequest"":{""MobileNumber"":""75484568"",""ProductNo"":""100"",""JsonFile"":{""dropdown"":[{""#para-id"":""2572"",""#new-code"":"""",""#text"":""This is first dropdown"",""option"":[{""#text"":""Option 1"",""#value"":""0""}]},{""#para-id"":""2584"",""#new-code"":"""",""#text"":""This is second dropdown"",""option"":[{""#text"":""Excellent"",""#value"":""2""}]},{""#para-id"":""2575"",""#new-code"":"""",""#text"":""This is third dropdown"",""option"":[{""#text"":""Not Available"",""#value"":""1""}]}]}}}";
Response response = JsonConvert.DeserializeObject<Response>(testJson);
var dropdowns = response.OnlineRequest.JsonFile;
string json = JsonConvert.SerializeObject(dropdowns, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class Option
{
[JsonProperty("#text")]
public string Text { get; set; }
[JsonProperty("#value")]
public string Value { get; set; }
}
public class Dropdown
{
[JsonProperty("#para-id")]
public string ParaId { get; set; }
[JsonProperty("#new-code")]
public string NewCode {
get{
if (this.Option.Count == 0)
{
return string.Empty;
}
return this.Option.First().Value;
}
}
[JsonProperty("#text")]
public string Text { get; set; }
[JsonProperty("option")]
public IList<Option> Option { get; set; }
}
public class JsonFile
{
[JsonProperty("dropdown")]
public IList<Dropdown> Dropdown { get; set; }
}
public class OnlineRequest
{
[JsonProperty("MobileNumber")]
public string MobileNumber { get; set; }
[JsonProperty("ProductNo")]
public string ProductNo { get; set; }
[JsonProperty("JsonFile")]
public JsonFile JsonFile { get; set; }
}
public class Response
{
[JsonProperty("onlineRequest")]
public OnlineRequest OnlineRequest { get; set; }
}
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).
We have to do some changes in existing JSON response and it requires to modify existing c# code too. Till now I've tried but don't get the exact idea about the formatting as it is new for me.
Can any one please check and suggest the changes in below code?
Existing JSON message:
"hotel_room_types": {
"QUEEN": {
"code": "QUEEN",
"bed_type": {
"standard": [
5
],
"custom": []
},
"extra_bed_type": {
"standard": [
5
],
"custom": []
},
"accessibility": "compliant_with_local_laws_for_disabled",
"room_smoking_policy": "non_smoking"
}
}
In above JSON message we have to replace the "bed_type" and "extra_bed_type" with "bed_configurations" and "extra_bed_configurations" in below newly provided format by client:
"hotel_room_types": {
"QUEEN": {
"code": "QUEEN",
"bed_configurations": [
[{
"type": "standard",
"code": 3,
"count": 1
}],
[{
"type": "standard",
"code": 1,
"count": 2
}]
],
"extra_bed_configurations": [
[{
"type": "standard",
"code": 900302,
"count": 1
},
{
"type": "custom",
"name": "Rollaway with wheel locks and adjustable height",
"count": 1
}]
],
"accessibility": "compliant_with_local_laws_for_disabled",
"room_smoking_policy": "non_smoking"
}
}
Existing C# code to generate the JSON response message format:
public class HotelRoomType
{
public string code { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Photo> photos { get; set; }
public Amenities room_amenities { get; set; }
public string room_size { get; set; }
public string room_size_units { get; set; }
public BedType bed_type { get; set; }
public BedType extra_bed_type { get; set; }
public RoomViewType room_view_type { get; set; }
public string accessibility { get; set; }
public MaxOccupancy max_occupancy { get; set; }
public string room_smoking_policy { get; set; }
}
Below is the code to fill the data in required fields of JSON message its inside a method which contains lines of code so I get it separately:
HotelRoomType hotelrmtype = new HotelRoomType();
hotelrmtype.bed_type = Common.GetStandardBedTypeMappingID(rm.BedType);
if (rm.NumOfBed > 1)
hotelrmtype.extra_bed_type = hotelrmtype.bed_type; //same as bed type
hotelrmtypeDict.Add(rm.Code, hotelrmtype); //Binding Data into Dictionary.
GetStandardBedTypeMappingID() contains :
public static CRS.TripConnect.BedType GetStandardBedTypeMappingID(short code)
{
CRS.TripConnect.BedType tripConnectBedType = new CRS.TripConnect.BedType();
List<int> standardBedTypes = new List<int>();
List<object> customBedTypes = new List<object>();
tripConnectBedType.standard = standardBedTypes;
tripConnectBedType.custom = customBedTypes; //These is blank.
short id = 0;
switch (code)
{
case 10:
id = 3;
break;
case 20: // 20 Queen Q 5
id = 5;
break;
case 30: // 30 Double D 1
id = 1;
break;
case 40: // 40 Twin T 8
id = 8;
break;
}
standardBedTypes.Add(id);
return tripConnectBedType;
}
Update: With the help of #Sam Answer below I have modified the code:
public class HotelRoomType
{
//Added following properties
public List<List<Bed_Configurations>> bed_configurations { get; set; }
public List<List<Extra_Bed_Configurations>> extra_bed_configurations { get; set; }
}
Created two new classes as:
public class Bed_Configurations
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
}
public class Extra_Bed_Configurations
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
public string name { get; set; }
}
Now the question is: How to fill these two list?
I'm trying to achieve this like below but it is giving me conversion error.
Bed_Configurations bdConfig = new Bed_Configurations();
bdConfig.type = "Standard";
bdConfig.code = Common.GetStandardBedTypeMappingIDnew(rm.BedType);
bdConfig.count = rm.NumOfBed;
hotelrmtype.bed_configurations.Add(bdConfig);
Error Message:
Please Advise the changes in the above code so as to get the required JSON message. Appreciate your help!
public class RootClass
{
public HotelRoomType hotel_room_types { get; set; }
}
public class HotelRoomType
{
public BedModelAndDetails QUEEN { get;set; }
}
public class BedModelAndDetails
{
public string accessibility { get; set; }
public string room_smoking_policy { get; set; }
public string code { get; set; }
//public BedType bed_type { get; set; }
public object bed_type { get; set; }
//public BedType extra_bed_type { get; set; }
public object extra_bed_type { get; set; }
public List<List<BedConfiguration>> bed_configurations { get; set; }
public List<List<BedConfiguration>> extra_bed_configurations { get; set; }
}
public class BedType
{
public List<int> standard { get; set; }
public List<int> custom { get; set; }
}
public class BedConfiguration
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
}
[TestMethod]
public void ReplaceJson()
{
var inputJson1 = "{\"hotel_room_types\": {\"QUEEN\": {\"code\": \"QUEEN\", \"bed_type\": {\"standard\": [5],\"custom\": [] }, \"extra_bed_type\": { \"standard\": [5], \"custom\": [] },\"accessibility\": \"compliant_with_local_laws_for_disabled\", \"room_smoking_policy\": \"non_smoking\" } " +"}}";
var input1 = JsonConvert.DeserializeObject<RootClass>(inputJson1, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
var inputJson2 = "{\"hotel_room_types\": {\"QUEEN\": {\"code\": \"QUEEN\",\"bed_configurations\": [[{\"type\": \"standard\",\"code\": 3,\"count\": 1}],[{\"type\": \"standard\",\"code\": 1,\"count\": 2}]],\"extra_bed_configurations\": [[{\"type\": \"standard\",\"code\": 900302,\"count\": 1},{\"type\": \"custom\",\"name\": \"Rollaway with wheel locks and adjustable height\",\"count\": 1}]],\"accessibility\": \"compliant_with_local_laws_for_disabled\",\"room_smoking_policy\": \"non_smoking\"} }}";
var input2 = JsonConvert.DeserializeObject<RootClass>(inputJson2);
//var finalInput = new RootClass();
//finalInput.hotel_room_types = inputJson1
//input1.hotel_room_types.QUEEN.bed_configurations = input2.hotel_room_types.QUEEN.bed_configurations;
//input1.hotel_room_types.QUEEN.extra_bed_configurations = input2.hotel_room_types.QUEEN.extra_bed_configurations;
input1.hotel_room_types.QUEEN.bed_type = input2.hotel_room_types.QUEEN.bed_configurations;
input1.hotel_room_types.QUEEN.extra_bed_type = input2.hotel_room_types.QUEEN.extra_bed_configurations;
}
Does this help?