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);
Related
I am using an API for car HP and PCP details. When API returns the response object it has some dynamic object and objects names depending upon the parameters given during JSON call input parameters. Please tell me how can I convert / deserialize this response object into C# object. I tried JSON convert to C# classes but didn't get required results. Given below in API response object. I need to parse this result object into C# object so i can use it for displaying required values on front end.
JSON Response / Result Object
{
"success": true,
"data": {
"hp": {
"58995": {
"48": {
"40": {
"9000": [
{
"balance": 58955,
"first": 1403.62,
"regular": 1403.62,
"final": 1413.62,
"total": 67423.76,
"charges": 8428.76,
"apr": 6.92,
"apr_nofees": 6.91,
"term": 48,
"flat": 3.57,
"fee_front": "0.00",
"fee_back": "10.00",
"fee_spread": 0,
"ref": "1000.00",
"ho": 0,
"ho_a": 0,
"sb": 0,
"id": "12",
"product_name": "HP/ML No Fees",
"excess_mileage": false
}
]
}
}
}
},
"pcp": {
"58995": {
"48": {
"40": {
"9000": [
{
"balance": 58955,
"first": 1251.04,
"regular": 1251.04,
"final": 8386,
"total": 68475.92,
"charges": 9480.92,
"apr": 6.89,
"apr_nofees": 6.89,
"rv": 8385,
"term": 48,
"flat": 3.56,
"rv_interest": 1084.68,
"charges_ex_rv": 8396.24,
"fee_front": "0.00",
"fee_back": "1.00",
"fee_spread": 0,
"ref": 0,
"ho": 0,
"ho_a": 0,
"sb": 0,
"id": "25",
"product_name": "BNP PCP",
"excess_mileage": "7p"
}
]
}
}
}
},
"count": 2,
"taken": 443
}
}
try this
var jsonParsed = JObject.Parse(json);
var count = (int)jsonParsed["data"]["count"];
var taken = (int)jsonParsed["data"]["taken"];
((JObject)jsonParsed["data"]).Descendants()
.OfType<JProperty>()
.Where(attr => attr.Name == "count" || attr.Name == "taken")
.ToList()
.ForEach(attr => attr.Remove());
Data data = jsonParsed.ToObject<Data>();
data.count = count;
data.taken = taken;
classes
public class Data
{
public bool success { get; set; }
public Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Product[]>>>>> data { get; set; }
public int count { get; set; }
public int taken { get; set; }
public class Product
{
public int balance { get; set; }
public double first { get; set; }
public double regular { get; set; }
public double final { get; set; }
public double total { get; set; }
public double charges { get; set; }
public double apr { get; set; }
public double apr_nofees { get; set; }
public int term { get; set; }
public double flat { get; set; }
public string fee_front { get; set; }
public string fee_back { get; set; }
public int fee_spread { get; set; }
[JsonProperty("ref")]
public string refer { get; set; }
public int ho { get; set; }
public int ho_a { get; set; }
public int sb { get; set; }
public string id { get; set; }
public string product_name { get; set; }
public object excess_mileage { get; set; }
}
I need to convert data from Json(String) to an object to use its properties. I am keep having a null value.
I checked the Json file and my classes and I don't see the possible reason for this problem. Can you please help me?`
This a part from the Json file:
{
"global": {
"#context": "http://environment.data.gov.uk/flood-monitoring/meta/context.jsonld",
"meta": {
"publisher": "Environment Agency",
"licence": "http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
"documentation": "http://environment.data.gov.uk/flood-monitoring/doc/reference",
"version": "0.6.1",
"comment": "Status: Beta service",
"hasFormat": [
"http://environment.data.gov.uk/flood-monitoring/id/stations.csv"
]
},
"items": [
{
"#id": "http://environment.data.gov.uk/flood-monitoring/id/stations/1029TH",
"RLOIid": "7041",
"catchmentName": "Cotswolds",
"dateOpened": "1994-01-01",
"easting": 417990,
"label": "Bourton Dickler",
"lat": 51.874767,
"long": -1.740083,
"measures": [
{
"#id": "http://environment.data.gov.uk/flood-monitoring/id/measures/1029TH-level-downstage-i-15_min-mASD",
"parameter": "level",
"parameterName": "Water Level",
"period": 900,
"qualifier": "Downstream Stage",
"unitName": "mASD"
},
{
"#id": "http://environment.data.gov.uk/flood-monitoring/id/measures/1029TH-level-stage-i-15_min-mASD",
"parameter": "level",
"parameterName": "Water Level",
"period": 900,
"qualifier": "Stage",
"unitName": "mASD"
}
],
"northing": 219610,
"notation": "1029TH",
"riverName": "Dikler",
"stageScale": "http://environment.data.gov.uk/flood-monitoring/id/stations/1029TH/stageScale",
"stationReference": "1029TH",
"town": "Little Rissington",
"wiskiID": "1029TH"
},
{
"#id": "http://environment.data.gov.uk/flood-monitoring/id/stations/E2043",
"RLOIid": "6022",
"catchmentName": "Welland",
"dateOpened": "1992-01-01",
"datumOffset": 2,
"easting": 528000,
"label": "Surfleet Sluice",
"lat": 52.845991,
"long": -0.100848,
"measures": [
{
"#id": "http://environment.data.gov.uk/flood-monitoring/id/measures/E2043-level-stage-i-15_min-mASD",
"parameter": "level",
"parameterName": "Water Level",
"period": 900,
"qualifier": "Stage",
"unitName": "mASD"
}
],
"northing": 329300,
"notation": "E2043",
"riverName": "River Glen",
"stageScale": "http://environment.data.gov.uk/flood-monitoring/id/stations/E2043/stageScale",
"stationReference": "E2043",
"town": "Surfleet Seas End",
"wiskiID": "L31004"
},
These are the classes:
namespace TechnicalTestZK
{
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("C:/Users/Zied/Desktop/Json.txt");
var ab = JsonConvert.DeserializeObject<Global>(json);
Console.WriteLine(ab.Items[0].RiverName);
//Console.WriteLine(GET("http://environment.data.gov.uk/flood-monitoring/id/floods"));
Console.ReadLine();
}
static string GET(string url)
{
System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
}
}
using Newtonsoft.Json;
namespace TechnicalTestZK
{
public class Meta
{
[JsonProperty("publisher")]
public string Publisher { get; set; }
[JsonProperty("licence")]
public string Licence { get; set; }
[JsonProperty("documentation")]
public string Documentation { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("comment")]
public string Comment { get; set; }
[JsonProperty("hasFormat")]
public string[] HasFormat { get; set; }
}
}
using Newtonsoft.Json;
namespace TechnicalTestZK
{
public class Measure
{
[JsonProperty("#id")]
public string Id { get; set; }
[JsonProperty("parameter")]
public string Parameter { get; set; }
[JsonProperty("parameterName")]
public string ParameterName { get; set; }
[JsonProperty("period")]
public int Period { get; set; }
[JsonProperty("qualifier")]
public string Qualifier { get; set; }
[JsonProperty("unitName")]
public string UnitName { get; set; }
}
}
using Newtonsoft.Json;
namespace TechnicalTestZK
{
public class Item
{
[JsonProperty("#id")]
public string Id { get; set; }
[JsonProperty("RLOIid")]
public string RLOIid { get; set; }
[JsonProperty("catchmentName")]
public string CatchmentName { get; set; }
[JsonProperty("dateOpened")]
public string DateOpened { get; set; }
[JsonProperty("easting")]
public int Easting { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("long")]
public string Long { get; set; }
[JsonProperty("measures")]
public Measure[] Measures { get; set; }
[JsonProperty("northing")]
public int Northing { get; set; }
[JsonProperty("notation")]
public string Notation { get; set; }
[JsonProperty("riverName")]
public string RiverName { get; set; }
[JsonProperty("stageScale")]
public string StageScale { get; set; }
[JsonProperty("stationReference")]
public string StationReference { get; set; }
[JsonProperty("town")]
public string Town { get; set; }
[JsonProperty("wiskiID")]
public string WiskiID { get; set; }
[JsonProperty("datumOffset")]
public float? DatumOffset { get; set; }
[JsonProperty("downstageScale")]
public string DownstageScale { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TechnicalTestZK
{
internal class Global
{
[JsonProperty("#context")]
public string #context { get; set; }
[JsonProperty("meta")]
public Meta Meta { get; set; }
[JsonProperty("items")]
public Item[] Items { get; set; }
}
}
The Json file you are trying to deserialize is one "level" higher than Global, which is what you are trying to deserialize into. Instead, make a new class that looks something like this:
public class GlobalContainer
{
[JsonProperty("global")]
public Global global { get; set; }
}
And deserialize into that by calling JsonConvert.DeserializeObject<GlobalContainer>(json)
Or you can use a json 2 # parser like http://json2csharp.com ;)
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?
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);
}
So im doing a HttpWebRequest which returns a jsonstring. The deserialized string looks like this:
{
"have_warnings": "20",
"pp_active": false,
"noofslots": 2,
"paused": true,
"pause_int": "0",
"mbleft": 7071.03378,
"diskspace2": 55.610168,
"diskspace1": 55.610168,
"jobs": [{
"timeleft": "0:00:00",
"mb": 6918.785553,
"msgid": "",
"filename": "xxxx",
"mbleft": 5869.015694,
"id": "xx"
},
{
"timeleft": "0:00:00",
"mb": 2238.526516,
"msgid": "",
"filename": "xxxx",
"mbleft": 1202.018086,
"id": "xxxx"
}],
"speed": "0 ",
"timeleft": "0:00:00",
"mb": 9157.312069,
"state": "Paused",
"loadavg": "0.11 | 0.08 | 0.08 | V=444M R=88M",
"kbpersec": 0.0
}
Now I want to display some of the data in a labels in my UI. What would be the best way to do this?
I tryed:
dynamic array = JsonConvert.DeserializeObject(qstatusOutput);
foreach (var item in array)
{
MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
}
But I get a error
'Newtonsoft.Json.Linq.JProperty' does not contain a definition for
'timeleft'
To take a type-safe approach you can use this site: http://json2csharp.com/
var root = JsonConvert.DeserializeObject<RootObject>(qstatusOutput);
foreach (var job in root.jobs)
{
Console.WriteLine(job.timeleft);
}
public class Job
{
public string timeleft { get; set; }
public double mb { get; set; }
public string msgid { get; set; }
public string filename { get; set; }
public double mbleft { get; set; }
public string id { get; set; }
}
public class RootObject
{
public string have_warnings { get; set; }
public bool pp_active { get; set; }
public int noofslots { get; set; }
public bool paused { get; set; }
public string pause_int { get; set; }
public double mbleft { get; set; }
public double diskspace2 { get; set; }
public double diskspace1 { get; set; }
public List<Job> jobs { get; set; }
public string speed { get; set; }
public string timeleft { get; set; }
public double mb { get; set; }
public string state { get; set; }
public string loadavg { get; set; }
public double kbpersec { get; set; }
}
but if you want to use dynamic then
dynamic array = JsonConvert.DeserializeObject(qstatusOutput);
foreach (var item in array.jobs)
{
MessageBox.Show(String.Format("{0} {1}", item.timeleft, item.mbleft));
}
time left is inside jobs so try below
foreach (var item in array.jobs)
{
MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
}
Your results from DeserializeObject is not the array. It's a structure that contains the array as one property.
dynamic result = JsonConvert.DeserializeObject(qstatusOutput);
dynamic array = result.jobs;
foreach (var item in array)
{
MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
}