c# JSON Parcing - c#

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

Related

deserialize nested complext types..c#

.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.

Put JSON data into c# datatable

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

Json.net deserialization is returning an empty object

I'm using the code below for serialization.
var json = JsonConvert.SerializeObject(new { summary = summary });
summary is a custom object of type SplunkDataModel:
public class SplunkDataModel
{
public SplunkDataModel() {}
public string Category { get; set; }
public int FailureCount { get; set; }
public Dictionary<string, SplunkError> FailureEntity { get; set; }
public Dictionary<string, string> JobInfo { get; set; }
public string JobStatus { get; set; }
public int SuccessCount { get; set; }
public List<string> SuccessEntity { get; set; }
public int TotalCount { get; set; }
}
Serialization results in the JSON below:
{
"summary": {
"Category": "category",
"JobStatus": "Failure",
"JobInfo": {
"Course processing failed": ""
},
"TotalCount": 0,
"SuccessCount": 0,
"FailureCount": 0,
"FailureEntity": {},
"SuccessEntity": []
}
}
Now, for unit testing purposes, I need to deserialize it, but the code below is returning an object with empty values. Where am I going wrong?
var deserialized = JsonConvert.DeserializeObject<SplunkDataModel>(contents);
On my side, it was because I had no public setter for my properties.
Instead of having
public class MyClass
{
public int FileId { get; }
}
I should have
public class MyClass
{
public int FileId { get; set; }
}
silly mistake that cost me hours....
When you serialized your SplunkDataModel to JSON, you wrapped it in an object with a summary property. Hence, when you deserialize the JSON back to objects, you need to use the same structure. There are several ways to go about it; they all achieve the same result.
Declare a class to represent the root level of the JSON and deserialize into that:
public class RootObject
{
public SplunkDataModel Summary { get; set; }
}
Then:
var deserialized = JsonConvert.DeserializeObject<RootObject>(contents).Summary;
Or, deserialize by example to an instance of an anonymous type, then retrieve your object from the result:
var anonExample = new { summary = new SplunkDataModel() };
var deserialized = JsonConvert.DeserializeAnonymousType(contents, anonExample).summary;
Or, deserialize to a JObject, then materialize your object from that:
JObject obj = JObject.Parse(contents);
var deserialized = obj["summary"].ToObject<SplunkDataModel>();

decode string from web to c# object - look the content value is incremented depending on count

Im having with the content. it is auto increment.
the result is static but the content is dynamic.
I'm using a hardcoded array in catching the return string from the web. Can anyone json decoder in converting the returned string to c# object
This is the returned string from web:
{
"result":{
"count":"3"
},
"content_1":{
"message_id":"23",
"originator":"09973206870",
"message":"Hello",
"timestamp":"2016-09-14 13:59:47"
},
"content_2":{
"message_id":"24",
"originator":"09973206870",
"message":"Test again.",
"timestamp":"2016-09-14 14:49:14"
},
"content_3":{
"message_id":"25",
"originator":"09973206870",
"message":"Another message",
"timestamp":"2016-09-14 14:49:20"
}
}
On site json2csharp.com you can generate classes for JSON data.
Generated classes needs some improvements and can look like:
public class Result
{
public string count { get; set; }
}
public class Content
{
public string message_id { get; set; }
public string originator { get; set; }
public string message { get; set; }
public string timestamp { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public Content content_1 { get; set; }
public Content content_2 { get; set; }
public Content content_3 { get; set; }
}
And using JSON.NET you can deserialize it:
public class Program
{
static public void Main()
{
string json = "{ \"result\":{ \"count\":\"3\" }, \"content_1\":{ \"message_id\":\"23\", \"originator\":\"09973206870\", \"message\":\"Hello\", \"timestamp\":\"2016-09-14 13:59:47\" }, \"content_2\":{ \"message_id\":\"24\", \"originator\":\"09973206870\", \"message\":\"Test again.\", \"timestamp\":\"2016-09-14 14:49:14\" }, \"content_3\":{ \"message_id\":\"25\", \"originator\":\"09973206870\", \"message\":\"Another message\", \"timestamp\":\"2016-09-14 14:49:20\" } }";
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(ro.content_1.message_id);
Console.WriteLine(ro.content_2.message_id);
}
}

RestSharp JSON Array deserialization

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

Categories