I launch this RestSharp query in JSON format:
var response = restClient.Execute<Report>(request);
The response I get contains this data
[
{
"Columns":
[
{"Name":"CameraGuid","Type":"Guid"},
{"Name":"ArchiveSourceGuid","Type":"Guid"},
{"Name":"StartTime","Type":"DateTime"},
{"Name":"EndTime","Type":"DateTime"},
{"Name":"TimeZone","Type":"String"},
{"Name":"Capabilities","Type":"UInt32"}
],
"Rows":
[
[
"00000001-0000-babe-0000-00408c71be50",
"3782fe37-6748-4d36-b258-49ed6a79cd6d",
"2013-11-27T17:52:00Z",
"2013-11-27T18:20:55.063Z",
"Eastern Standard Time",
2147483647
]
]
}
]
I'm trying to deserialize it into this group of classes:
public class Report
{
public List<ReportResult> Results { get; set; }
}
public class ReportResult
{
public List<ColumnField> Columns { get; set; }
public List<RowResult> Rows { get; set; }
}
public class ColumnField
{
public string Name { get; set; }
public string Type { get; set; }
}
public class RowResult
{
public List<string> Elements { get; set; }
}
Unfortunately, the result data is null and I get this exception:
Unable to cast object of type 'RestSharp.JsonArray' to type
'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
I cannot figure out what is wrong here.
I little help would be greatly appreciated.
Try this:
var response = restClient.Execute<List<ReportResult>>(request);
EDIT
You should also change ReportResult to:
public class ReportResult
{
public List<ColumnField> Columns { get; set; }
public List<List<string>> Rows { get; set; }
}
and you can get rid of Report and RowResult.
There is another way by creating wrapper class:
public class ThirdPartySuggesters : List<ThirdPartySuggester> {}
var response = client.Execute<ThirdPartySuggesters>(request);
Related
I need a little assistance in obtaining values from a JSON object in C#. Here is the code and the output. I am trying to retrieve value of ScoreRepresentation from both the objects. The obtained values in this case would be BR400L and null as per the below output.
Can anyone please assist? Newbie in C# :) Thanks in advance
using System;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var json = "{\"Results\":[{\"RequestIdentifier\":\"Lexile\",\"ValueType\":\"INTEGER\",\"Scores\":[{\"lexile\":{\"ScoreValue\":-400,\"ScaledScore\":-400,\"ScoreRepresentation\":\"BR400L\"}}]},{\"RequestIdentifier\":\"UnifiedScaleScore\",\"ValueType\":\"INTEGER\",\"Scores\":[{\"unifiedScaleScore\":{\"ScoreValue\":610,\"ScaledScore\":610,\"ScoreRepresentation\":null}}]}]}";
var deserialized = JsonConvert.DeserializeObject(json);
Console.WriteLine(deserialized);
}
}
}
Output:
{
"Results": [
{
"RequestIdentifier": "Lexile",
"ValueType": "INTEGER",
"Scores": [
{
"lexile": {
"ScoreValue": -400,
"ScaledScore": -400,
"ScoreRepresentation": "BR400L"
}
}
]
},
{
"RequestIdentifier": "UnifiedScaleScore",
"ValueType": "INTEGER",
"Scores": [
{
"unifiedScaleScore": {
"ScoreValue": 610,
"ScaledScore": 610,
"ScoreRepresentation": null
}
}
]
}
]
}
I like to go the "Model" route. You create models of your data, then you can easily deserialize to them. Sometimes when I am feeling lazy, I will use this site to do my work for me.
So, for your specific example, it gives back these models:
public class Lexile {
public int ScoreValue { get; set; }
public int ScaledScore { get; set; }
public string ScoreRepresentation { get; set; }
}
public class UnifiedScaleScore {
public int ScoreValue { get; set; }
public int ScaledScore { get; set; }
public object ScoreRepresentation { get; set; }
}
public class Score {
public Lexile lexile { get; set; }
public UnifiedScaleScore unifiedScaleScore { get; set; }
}
public class Result {
public string RequestIdentifier { get; set; }
public string ValueType { get; set; }
public List<Score> Scores { get; set; }
}
public class Root {
public List<Result> Results { get; set; }
}
Then, you can simply deserialize to Root by doing this:
var deserialized = JsonConvert.DeserializeObject<Root>(json);
Keep in mind that if your JSON is not perfect, you will find some inconsistencies with the output. You may have to massage your models a bit to fix those issues. You can't just assume that site gives you 100% accurate data.
But, if it's good enough, you can now get at every property you'd ever need to without having to putz around with dynamics or JToken.
For example:
foreach(var r in deserialized.Results)
{
foreach(var s in r.Scores)
{
Console.Write(s.unifiedScaleScore.ScoreRepresentation);
}
}
I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me
I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?
{
"objects": {
"UserRequest::567": {
"code": 0,
"message": "created",
"class": "UserRequest",
"key": "567",
"fields": {
"ref": "R-000567",
"org_id": "4"
}
}
}
}
The question is what are the best practices to read through this kind of a json string?
Thank you
To Deserialize this using Newtonsoft.Json, here are the classes:
public class CreateRequest
{
public long code { get;set; }
public string message { get; set; }
[JsonProperty("class")]
public string class1 { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
[JsonProperty("ref")]
public string refe { get; set; }
public string org_id { get; set; }
}
public class Root
{
public Dictionary<string, CreateRequest> objects { get; set; }
//The 'string' key in the dictionary is the 'UserRequest::567'
}
Then to Deserialize use:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;
Im having trouble in parsin JSON in C#. I want to parse this Json Format.
{
"data":
[
{
"id": 3,
"code": "0000004",
}
]
}
Here is my code in C#.
public Data data { get; set; }
public class Data
{
public string id { get; set; }
public string code { get; set; }
}
The JSON shown is an object that has (as data) an array of elements that have an id and code, so:
public class SomeRoot {
public List<Data> data {get;} = new List<Data>();
}
and deserialize a SomeRoot and you should be fine:
var root = JsonConvert.DeserializeObject<SomeRoot>(json);
var obj = root.data[0];
Console.WriteLine(obj.id);
Console.WriteLine(obj.code);
You are missing an essential part, the outer object. Also, the data is an array:
public class RootObject
{
public Data[] data { get; set; }
}
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
Next time, follow the steps as outlined in Easiest way to parse JSON response. It will help you generate the correct class.
It should be :
public class Data
{
public int id { get; set; }
public string code { get; set; }
}
public class RootObject
{
public List<Data> data { get; set; }
}
.NET 4.6.1
I have a json string:
{
"success": true,
"rows": [
{
"meter_id": "10443720003987688"
}]
}
Here's my class:
public class ESIIDClass
{
public bool success { get; set; }
public Rows rows { get; set; }
}
public class Rows
{
public string meter_id { get; set; }
}
I deserialize the string like so:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var esiid = json_serializer.Deserialize<ESIIDClass>(theJSONstring);
But this throws an error:
System.InvalidOperationException: Type 'WebAPI.Controllers.Rows' is not
supported for deserialization of an array.
How do I deserialize nested complex types? Thanks
You class should be named Row, as it represents a single Row (it's not pural).
public class Row
In json, rows is clearly an array:
"rows": [
So your class should reflect that:
public Row[] rows { get; set; }
you can try
public class ESIIDClass
{
public bool success { get; set; }
public Rows[] rows { get; set; }
}
or
public class ESIIDClass
{
public bool success { get; set; }
public List<Rows> rows { get; set; }
}
The json key-value pair's value with [] will map the C# type inherited from IEnumerable.
I am trying to deserialise some JSON that I get back from an API so that I can loop through an array of county names and add the information to a datatable in C#. However I am receiving following error at the first hurdle when I try and deserialise it:
error: System.MissingMethodException: No parameterless constructor defined for type of 'DPDJSONLibrary.DPD_JSON+LOCR_Data[]'.
The provider of the API provides an example of the JSON response as follows:
{
"error": null,
"data":[{
"country": [{
"countryCode":"GB",
"countryName":"United Kingdom",
"internalCode":"UK",
"isEUCountry":false,
"isLiabilityAllowed":false,
"isoCode":"826",
"isPostcodeRequired":false,
"liabilityMax":15000
}]
}]
}
A sample of the JSON data I am getting back from the API is:
{
"data": {
"country":[
{
"countryCode":"PM",
"countryName":"St Pierre & Miquilon",
"isoCode":"666",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SR",
"countryName":"Suriname",
"isoCode":"740",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SZ",
"countryName":"Swaziland",
"isoCode":"748",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
}
]
}
}
I have tried to make some classes to put the JSON in as follows:
/// <summary>
/// List Of Countries Response object.
/// </summary>
public class LOCR
{
public LOCR_Error error { get; set; }
public LOCR_Data[] data { get; set; }
}
public class LOCR_Error
{
public string errorAction { get; set; }
public string errorCode { get; set; }
public string errorMessage { get; set; }
public string errorObj { get; set; }
public string errorType { get; set; }
}
public class LOCR_Data
{
public LOCR_Data_Country[] country { get; set; }
}
public class LOCR_Data_Country
{
public string countryCode { get; set; }
public string countryName { get; set; }
public string internalCode { get; set; }
public bool isEUCountry { get; set; }
public bool isLiabilityAllowed { get; set; }
public string isoCode { get; set; }
public bool isPostcodeRequired { get; set; }
public int liabilityMax { get; set; }
}
When I get the JSON back as a string, I am trying to use the Newtonsoft (plugin?) to put it into my classes using:
JavaScriptSerializer ser = new JavaScriptSerializer();
DPD_JSON.LOCR DPDCountries = new DPD_JSON.LOCR();
DPDCountries = ser.Deserialize<DPD_JSON.LOCR>(data);
It is the last line above that is generating the error. I suspect I've written my classes wrong that I am trying to deserialise the JSON in to - can anyone see where I've gone wrong?
Deserialize will return a list and not an array, So your LOCR_Data_Country should be of type List and not array:
public class LOCR_Data
{
public List<LOCR_Data_Country> country { get; set; }
}
There's a HUGE difference between the two example JSON strings you've shown. Mainly the first one is an array : "data":[ ... ] and the second one is an object "data:{ ... }. These two are not interchangeable so you have to stick to either one of those. If the thing you're getting back from the API is an object instead you should rewrite your model to be :
public class LOCR
{
public LOCR_Error error { get; set; }
// object here since "data": { ... }
public LOCR_Data data { get; set; }
}
And as you move further with the JSON you can see that LOCR_Data.country is in fact an array in both cases "country": [ ... ] so you can stick with the current implementation of LOCR_Data class.
Try Using :
YourResultClass object = JsonConvert.DeserializeObject<YourResultClass>(Jsonstring);
See the answer of this Using JsonConvert.DeserializeObject to deserialize Json
OR
dynamic data = Json.Decode(json);
You can refer this Deserialize JSON into C# dynamic object? for further assistance