deserialize nested complext types..c# - 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.

Related

Dynamic json property deserialize

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;

Deserialize json object with dynamic items in C#

I've got the following json document:
{
"name": "bert",
"Bikes": {
"Bike1": {
"value": 1000,
"type": "Trek"
},
"Bike2": {
"value": 2000,
"type": "Canyon"
}
}
}
With potentially other bikes like Bike3...BikeN. I want to deserialize to C# objects. Problem is that in the deserialization step the bikes data is completely lost, resulting in a null Bikes collection.
Code to reproduce:
[Test]
public void FirstCityJsonParsingTest()
{
var file = #"./testdata/test.json";
var json = File.ReadAllText(file);
var res = JsonConvert.DeserializeObject<Person>(json);
Assert.IsTrue(res.Name == "bert");
// next line is failing, because res.Bikes is null...
Assert.IsTrue(res.Bikes.Count == 2);
}
public class Bike
{
public string Id { get; set; }
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Name { get; set; }
public List<Bike> Bikes { get; set; }
}
To fix this problem a change in the used model is necessary. But what change is needed here to fill the bikes data correctly?
Note: Changing the input document is not an option (as it's a spec)
Your code structure is not reflecting your json. Common approach to deserializing json with dynamic property names is to use Dictionary<string, ...> (supported both by Json.NET and System.Text.Json). Try the following:
public class Bike
{
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Bike> Bikes { get; set; }
}
Person.Bikes should be changed to Dictionary<string, Bike> (also Bike.Id property is not needed) cause Bikes json element is not an array but object.

c# JSON Parcing

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

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

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