How to set value to JSON to based on #value - c#

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; }
}

Related

Deserialize JSON in xamarin

How can i deserialize a local json file to an object?
I'm trying to deserialize a local json file in xamarin but it just doesn't work i read many guides and watched some tutorials but none of them helped and most of them give the same code i'm using right now
My code:
public test()
{
InitializeComponent();
List<Rootobject> ob = new List<Rootobject>();
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(test)).Assembly;
Stream stream = assembly.GetManifestResourceStream($"TunisiaPrayer.states.json");
string text = "";
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
ob = JsonConvert.DeserializeObject<List<Rootobject>>(text);
//printing the json file to make sure it read it fully
//i get no error here
DisplayJson.Text = text;
//try catch to test if it was deserialized or not
try
{
//printing a property of ob in a label element to see if it works
DisplayData.Text = ob[2].Property1.data.gouvernorat.intituleAn;
}
catch (Exception ex)
{
DisplayData.Text = ex.Message;
}
}
RootObject Class:
namespace TunisiaPrayer.Models
{
public class Rootobject
{
public Class1 Property1 { get; set; }
}
public class Class1
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public Delegation[] delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
}
sample of states.json:
[{
"data": {
"gouvernorat": {
"id": 358,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
"delegation": [{
"id": 631,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
{
"id": 534,
"intituleAr": "التظامن",
"intituleAn": "Attadhamon"
},
{
"id": 532,
"intituleAr": "سكرة",
"intituleAn": "Soukra"
}
]
}
},
{
"data": {
"gouvernorat": {
"id": 362,
"intituleAr": "القصرين",
"intituleAn": "Kasserine"
},
"delegation": [{
"id": 579,
"intituleAr": "العيون",
"intituleAn": "El Ayoun"
},
{
"id": 576,
"intituleAr": "سبيبة",
"intituleAn": "Sbiba"
},
{
"id": 575,
"intituleAr": "سبيطلة",
"intituleAn": "Sbitla"
},
{
"id": 573,
"intituleAr": "تالة",
"intituleAn": "Tala"
}
]
}
}]
error: Object reference not set to an instance of an object
note that when i print ob.Count it gives me the correct length of the list but i can't access any data in it
you have to use Root[] , not just root, try this
var obj =JsonConvert.DeserializeObject< List<Root>>(text);
test
var displayData = obj[1].data.gouvernorat.intituleAn; // = Kasserine
classes
public class Root
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public List<Delegation> delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}

JSON object throws up null response but it isn't null

Tried to parse JSON object using JavaScriptSerializer().Deserialize but getting thrown a null error at foreach (var item in getRoute.results) where Route getRoute = new JavaScriptSerializer().Deserialize<Route>(strresulttest);
The thing is, when I debugged strresulttest by printing out its contents, I was able to see my expected JSON output as shown here https://codeshare.io/5vM6X4
Code to parse JSON:
public class Route
{
public List<GetRoute> results { get; set; }
}
public class GetRoute
{
public string status_message { get; set; }
public string viaRoute { get; set; }
public string subtitle { get; set; }
public int totalTime { get; set; }
public int totalDistance { get; set; }
}
private void GetInstructions()
{
//GET METHOD for route query
string strurltest = String.Format("https://developers.onemap.sg/privateapi/routingsvc/route?start="+
startLat+","+ startLon +"&end="+ destinationLat +","+ destinationLon+"&"+
"routeType="+ transportType + "&token="+token);
WebRequest requestObjGet = WebRequest.Create(strurltest);
requestObjGet.Method = "GET";
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strresulttest = null;
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
//reminder: remove after prod. GET is working.
System.Diagnostics.Debug.WriteLine(strresulttest);
sr.Close();
}
//display search recommendations
Route getRoute = new JavaScriptSerializer().Deserialize<Route>(strresulttest);
foreach (var item in getRoute.results)
{
//reminder: remove after prod.
System.Diagnostics.Debug.WriteLine("Route via: " + item.viaRoute + "\n");
System.Diagnostics.Debug.WriteLine("Description: " + item.subtitle + "\n");
}
}
Expected JSON output (shown when System.Diagnostics.Debug.WriteLine(strresulttest);):
{
"status_message": "Found route between points",
"route_geometry": "m{`G_cyxRaAmALMtAyAj#g#RIZG|#KTC??RCxBQ\\KAOa#sDAQWwBM_AUmBEa#Ky#_#kDKoAIgAAs#Ce#?M|#_#PINUFk#Ik#e#aCu#wBeBoD_A}AmBqC{#iA_AeAyAqA{LmKmAu#k#g#y#Jk#r#k#r#GP#PFJhAt#oEnGw#i#QTMPs#g#}AzBr#d#JQ",
"status": 0,
"route_instructions": [
[
"Head",
"SINARAN DRIVE",
56,
"1.320394,103.844478",
18,
"56m",
"North East",
"North",
"driving",
"Head Northeast On Sinaran Drive"
],
[
...
],
...
],
"route_name": [
"MOULMEIN ROAD",
"WHAMPOA ROAD"
],
"route_summary": {
"start_point": "SINARAN DRIVE",
"end_point": "WHAMPOA ROAD",
"total_time": 390,
"total_distance": 2675
},
"viaRoute": "JALAN BAHAGIA",
"subtitle": "Fastest route, assuming usual traffic",
"phyroute": {
"status_message": "Found route between points",
"route_geometry": "m{`G_cyxRaAmALMtAyAj#g#RIZG|#KTC??Ao#BcB?kCBIHK|Ay#M_AUmBEa#Ky#_#kDKoAIgAAs#Ce#?M?OBw#BsCEq#Q{#Qm#KQGMaCNM#iFXO?sCNo#LCa#QaICe#EI?EBQTi#Ha##c#CMGWOYOOgEgD{BeBuB}AoEnGw#i#QTMPs#g#}AzBr#d#JQ",
"status": 0,
"route_instructions": [
[
"Head",
"SINARAN DRIVE",
56,
"1.320394,103.844478",
18,
"56m",
"North East",
"North",
"driving",
"Head Northeast On Sinaran Drive"
],
[
...
],
...
],
"route_name": [
...
],
"route_summary": {
...
},
"viaRoute": "BALESTIER ROAD",
"subtitle": "Shortest distance"
}
}
You are getting a null in results because the class structure that you are deserializing into does not match your JSON. The JSON you linked in your question corresponds to this class structure instead:
public class Route
{
public string status_message { get; set; }
public string route_geometry { get; set; }
public int status { get; set; }
public List<List<object>> route_instructions { get; set; }
public List<string> route_name { get; set; }
public RouteSummary route_summary { get; set; }
public string viaRoute { get; set; }
public string subtitle { get; set; }
public Phyroute phyroute { get; set; }
}
public class RouteSummary
{
public string start_point { get; set; }
public string end_point { get; set; }
public int total_time { get; set; }
public int total_distance { get; set; }
}
public class Phyroute
{
public string status_message { get; set; }
public string route_geometry { get; set; }
public int status { get; set; }
public List<List<object>> route_instructions { get; set; }
public List<string> route_name { get; set; }
public RouteSummary route_summary { get; set; }
public string viaRoute { get; set; }
public string subtitle { get; set; }
}
You can deserialize and get the viaRoute and subtitle like this:
Route route = new JavaScriptSerializer().Deserialize<Route>(strresulttest);
System.Diagnostics.Debug.WriteLine("Route via: " + route.viaRoute);
System.Diagnostics.Debug.WriteLine("Description: " + route.subtitle);

Change existing JSON message format into new with fields in C#?

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?

Deserialization Json to C# using Newtonsoft

I have the following JSON that I need to parse :
{
"code": 200,
"status": "OK",
"response": {
"course_accessJSON": null,
"in_progress": 1,
"completed": 0,
"passed": 0,
"location": "http://*************************************",
"subscription": {
"started": 1465834293,
"expired": 1473869493,
"payment": "account"
},
"is_expired": false,
"course_progress": {
"CMP1044": {
"course_name_en": "Java Programming",
"no_of_lessons": 30,
"viewed": 1,
"viewed_start": 1465834789,
"viewed_end": null,
"cert_attemptsCSV": null,
"cert_resetsCSV": null,
"cert_serial": null,
"high_score": null,
"location": "http://***************************"
}
}
}
}
I have managed to get all the elements out except the value in the course_progress item using the following:
SampleResourse obj = JsonConvert.DeserializeObject<SampleResourse>(s);
Response.Write(obj.Response.CourseProgress.CMP1044.CourseNameEn.ToString());
class SampleResourse
{
[JsonProperty("code")]
public int respcode { get; set; }
[JsonProperty("status")]
public string respStatus { get; set; }
[JsonProperty("response")]
public Response2 Response { get; set; }
}
class Response2
{
[JsonProperty("in_progress")]
public int InProgress { get; set; }
[JsonProperty("completed")]
public int Completed { get; set; }
[JsonProperty("passed")]
public int Passed { get; set; }
[JsonProperty("course_progress")]
public CourseProgress CourseProgress { get; set; }
}
class CourseProgress
{
[JsonProperty("CMP1044")]
public CMP10442 CMP1044 { get; set; }
}
class CMP10442
{
[JsonProperty("course_name_en")]
public string CourseNameEn { get; set; }
}
I need the elements course_name_en, no_of_lessons,viewed however there will be multiple properties similar to "CMP1044". Each "CMP" property will have a unique number. I want to list progress on each.
Simply change the following :
class Response2
{
[JsonProperty("in_progress")]
public int InProgress { get; set; }
[JsonProperty("completed")]
public int Completed { get; set; }
[JsonProperty("passed")]
public int Passed { get; set; }
[JsonProperty("course_progress")]
public Dictionary<string, CourseProgress> CourseProgress { get; set; }
}
class CourseProgress
{
[JsonProperty("course_name_en")]
public string CourseNameEn { get; set; }
}
To list the course name along with the id, you can do this:
var resource = Newtonsoft.Json.JsonConvert.DeserializeObject<SampleResourse>(json);
foreach (var kvp in resource.Response.CourseProgress)
{
Response.Write(kvp.Key + ":" + kvp.Value.CourseNameEn + Environment.NewLine);
}

C#, json .net - value of the two words

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; }
}

Categories

Resources