Multi-Object JSON, "Cannot deserialize the current JSON object" - c#

Okay first of all, the answer is probably very simple... But after 45 minutes of trying and googling I just can't figure it out!
So I have some problems getting this Json to parse correctly. I created the classes with http://json2csharp.com/ only it doesn't tell me the code to parse it.
My current classes:
public class Representations
{
public string thumb { get; set; }
public string large { get; set; }
public string full { get; set; }
}
public class Search
{
public string id { get; set; }
public string file_name { get; set; }
public Representations representations { get; set; }
}
public class SearchQuery
{
public List<Search> search { get; set; }
public int total { get; set; }
}
JSON:
{
"search": [
{
"id": "0300",
"file_name": "0300.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0300.jpg"
},
},
{
"id": "0000",
"file_name": "0000.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0000.jpg"
},
},
{
"id": "0d00",
"file_name": "0d00.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0d00.jpg"
},
}
],
"total": 3
}
and code:
searchresults = JsonConvert.DeserializeObject<List<SearchQuery>>(JSONCode);

You should deserialize to a SearchQuery, not List<SearchQuery>:
SearchQuery result = JsonConvert.DeserializeObject<SearchQuery>(JSONCode);
and then use the search property to access the list of search results:
List<Search> searchResults = result.search;

Related

Complicated Json to C# Object Deserialize with classes

I am trying to deserialize a json response I get from a web call. I have it 90 percent figured out. The only part I am having a hard time figuring out is there are these json arrays which have data in them and each array name is unique using the email address. I have not been able to figure out how to turn the Email Arrays into 1. Dynamic and having it create many lists or just a couple depending on what comes back in the response and also dynamically naming the list arrays to put the data into the Records class.
As you can see in the Records class I need this to be more dynamic and flexible to receive any and all emails.
Below is the json:
{
"result": {
"records": {
"joeblow#gmail.com": [
{
"OrderId": "d9535109-d305-4584-a503-8194bbcfcff2",
"CompletedOrderId": "BCFCFF2",
"CustomerId": 1212,
"CompletedTime": "2020-10-26 13:32:02",
"Email": "joeblow#gmail.com",
"ShippingFirstName": "Joe",
"ShippingMiddleName": "",
"ShippingLastName": "Blow",
"LineItems": {
"tfl.es.bluray": { "qty": 1 },
"booklets.en.ebook": { "qty": 1 }
}
}
],
"cleob#hotmail.com": [
{
"OrderId": "7bf97b3a-bc46-411c-bc30-12563326dba0",
"CompletedOrderId": "326DBA0",
"CustomerId": 1212,
"CompletedTime": "2020-10-26 20:07:44",
"Email": "cleob#hotmail.com",
"ShippingFirstName": "Cleo",
"ShippingMiddleName": "",
"ShippingLastName": "Blue",
"LineItems": {
"tfl.es.bluray": { "qty": 1 },
"booklets.en.ebook": { "qty": 1 },
"aos.en.pb": { "qty": 1 },
"course-tos.en.olr": { "qty": 1 },
"pow-hsk-nofilm.en.combo": { "qty": 1 },
"course-organizing.en.olr": { "qty": 1 }
}
}
],
"johnd#gmail.com": [
{
"OrderId": "630f0dda-94c3-4b82-a070-2554004dce29",
"CompletedOrderId": "04DCE29",
"CustomerId": 12345,
"CompletedTime": "2020-10-25 21:52:04",
"Email": "johnd#gmail.com",
"ShippingFirstName": "John",
"ShippingMiddleName": "",
"ShippingLastName": "Doe",
"LineItems": {
"tfl.es.bluray": { "qty": 1 },
"booklets.en.ebook": { "qty": 1 },
"aos.en.pb": { "qty": 1 },
"course-tos.en.olr": { "qty": 1 },
"pow-hsk-nofilm.en.combo": { "qty": 1 },
"course-organizing.en.olr": { "qty": 1 },
"oak-2007.en.cd": { "qty": 1 }
}
}
]
},
"errors": [
{
"id": "bademailaddress-yahoo.com",
"message": "Email address 'bademailaddress-yahoo.com' is not a valid email address"
}
]
},
"jsonrpc": "2.0",
"id": 12345634523
}
And the classes I made for the json deserialization:
public partial class JsonEmailDeSerializer
{
[JsonProperty("result")]
public Result Result { get; set; }
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
}
public partial class Result
{
[JsonProperty("records")]
public Records Records { get; set; }
[JsonProperty("errors")]
public List<Error> Errors { get; set; }
}
public partial class Error
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
public partial class Records
{
[JsonProperty("joeblow#gmail.com")]
public List<MailCom> JoeblowGmailCom { get; set; }
[JsonProperty("cleob#hotmail.com")]
public List<MailCom> CleobHotmailCom { get; set; }
[JsonProperty("johnd#gmail.com")]
public List<MailCom> JohndGmailCom { get; set; }
}
public partial class MailCom
{
[JsonProperty("OrderId")]
public Guid OrderId { get; set; }
[JsonProperty("CompletedOrderId")]
public string CompletedOrderId { get; set; }
[JsonProperty("CustomerId")]
public long CustomerId { get; set; }
[JsonProperty("CompletedTime")]
public DateTimeOffset CompletedTime { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("ShippingFirstName")]
public string ShippingFirstName { get; set; }
[JsonProperty("ShippingMiddleName")]
public string ShippingMiddleName { get; set; }
[JsonProperty("ShippingLastName")]
public string ShippingLastName { get; set; }
[JsonProperty("LineItems")]
public Dictionary<string, LineItem> LineItems { get; set; }
}
public partial class LineItem
{
[JsonProperty("qty")]
public long Qty { get; set; }
}
public partial class JsonEmailDeSerializer
{
public static JsonEmailDeSerializer FromJson(string json) => JsonConvert.DeserializeObject<JsonEmailDeSerializer>(json, FedExShipper.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this JsonEmailDeSerializer self) => JsonConvert.SerializeObject(self, FedExShipper.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
Common approach to deserializing json with dynamic property names is to use Dictionary<string, ...>, in this case - Dictionary<string, List<MailCom>> can be used for Records property:
public partial class Result
{
[JsonProperty("records")]
public Dictionary<string, List<MailCom>> Records { get; set; }
[JsonProperty("errors")]
public List<Error> Errors { get; set; }
}
Json.NET can treat json object properties as keys for dictionary which makes it suitable to deserialize such dynamic data. The same is true for System.Text.Json.
That will never serialize to a class properly.
You'll have to use a lower-level API like Utf8JsonReader to read that level in the document, at least.

Getting NULL Deserializing JSON string using JavaScriptSerializer

Hi I having following JSON but while Using Deserialize method getting NULL in nested Member here is the sample JSON and corresponding Class object:
{
"status": "success",
"Info": [
{
"Name": "1099589",
"version": "Current Version",
"MoreDetails": [
{
"Name": "1099589",
"state": "IN"
},
{
"Name": "1099768",
"state": "OUT"
}
]
},
{
"Name": "1099768",
"version": "2019"
}
],
"errorCode": "",
"message": ""
}
Class :
public class MoreDetail
{
public string Name { get; set; }
public string state { get; set; }
}
public class Info
{
public string Name { get; set; }
public string version { get; set; }
public IList<MoreDetail> MoreDetails { get; set; }
}
public class Example
{
public string status { get; set; }
public IList<Info> Info { get; set; }
public string errorCode { get; set; }
public string message { get; set; }
}
While I am using
JavaScriptSerializer js = new JavaScriptSerializer();
Example ex = new OfferingPayload();
ex = js.Deserialize<Example> (jsonstring);
I am able to see Example object having Info data as list but MoreDetails member of Info Class is coming NULL.
Can someone suggest what I am missing here ?
Thats because your second "Info" object doesnt have "MoreDetails" property.
{
"Name": "1099768",
"version": "2019"
}
To make it works you can add an empty "MoreDetails" property to your json.
{
"Name": "1099768",
"version": "2019",
"MoreDetails": []
}
Or you can configure your serializer to handle this property as optional. Then it will works fine even if it missing in your json.

Pick out specific, optional key from metavalues object in JSON and store into my class

I'm struggling to make this conversion happen, and not sure it's entirely feasible. My JSON from a third party could look like this:
{
"equipments": [
{
"serialNumber": "11-17-053",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1508856453875,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59ef52854d40a9009c787596"
},
{
"serialNumber": "11-17-054",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1508856453875,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59ef52854d40a9009c787597"
},
{
"serialNumber": "8-17-022",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1505326964589,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59b9777480e426009d01d48d"
},
{
"serialNumber": "22A-17-001",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1504908025733,
"fieldOffice_id": "58b74b080c206710004ff726",
"clients_id": [
"59bbfdf5725cd00012fb15d8"
],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33122
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
},
"g99idmcqyuo2na9e6l": "YARD",
"709pm94prt2tpjt90y": 5,
"bgen1h4i5b6f8xa1kh": "9/8/2017 7:18:24 PM",
"yvtvsl8dedudqjtdud": "0.00000, 0.00000",
"aj3h2b5fdbic9s72m3": "Parex",
"8wt1re82xidjiv8rzi": "YARD"
},
"schedules": [],
"id": "59b312f93256d5009c4a73fb"
},....
This is obviously not a complete example, but should help get my question across.
Is there a way to create a C# class that pulls in certain fields only if they exist from the "metavalues" array?
My current class is as follows which works to get the data, but not exactly how I want.
public class Equipment
{
[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }
public string equipmentType_id { get; set; }
public bool isInService { get; set; }
public List<string> clients_Id { get; set; }
public string fieldOffice_id { get; set; }
[JsonProperty("id")]
public string EquipmentId { get; set; }
[JsonProperty("metavalues")]
public Dictionary<string, object> metavalues { get; set; }
}
What I'm after, is taking the key of "g99idmcqyuo2na9e6l" which is optional in the metavalues, and store it in a property called "LeaseName".
I tried the following to no avail.
public class Equipment
{
[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }
public string equipmentType_id { get; set; }
public bool isInService { get; set; }
public List<string> clients_Id { get; set; }
public string fieldOffice_id { get; set; }
[JsonProperty("id")]
public string EquipmentId { get; set; }
[JsonProperty("g99idmcqyuo2na9e6l")]
public string LeaseName { get; set; }
}
If I try to make a class for the metavalues section, I get an exception indicating that JSON.NET can't convert it to my object, hence why I used the Dictionary<string, object> option.
EDIT # 1: The accepted answer works for me, but for those who stumble upon this and truly need a property name from a nested array you could try the following.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (metavalues != null)
{
if (metavalues.ContainsKey("g99idmcqyuo2na9e6l"))
{
string _LeaseName = (string)metavalues["g99idmcqyuo2na9e6l"];
LeaseName = _LeaseName;
}
}
}
I think my edit approach is a bit overkill but just throwing this out there.
Yes, this is possible, but since the lease value is still one level down in the JSON you need an intermediate class to hold it (to replace the dictionary).
public class Equipment
{
...
[JsonProperty("metavalues")]
public MetaValues MetaValues { get; set; }
}
public class MetaValues
{
[JsonProperty("g99idmcqyuo2na9e6l")]
public string LeaseName { get; set; }
}
Fiddle: https://dotnetfiddle.net/Ddqzc7

Creating a class in JSON.NET to deserialize a given JSON

I need an example how of to build a class for a JSON response with JSON.NET.
I am calling the following, that requires a class ResponseCall that I have to build:
JsonConvert.DeserializeObject<ResponseCall>(result);
My problem is that I am not sure what exactly are all the nested attributes in a class. What is "responseHeader" and the nested attributes "Status" and how do I access them?
Here is the JSON:
{
"responseHeader": {
"status": 0,
"QTime": 1801,
"params": {
"fl": "id_tlc,ccZzcucbez_tlc,ekonr_tlc,gtin_tlc,region_tlc",
"sort": "ccZzcucbez_tlc asc",
"indent": "on",
"start": "0",
"q": "indexName:b2cLMIVProdukteIndex AND ( (id_tlc:*000006757 OR gtin_tlc:6757 OR (addGtin_tlc:6757,* OR addGtin_tlc:*,6757,* OR addGtin_tlc:*,6757 ) OR ekonr_tlc:6757))",
"wt": "json",
"qt": "",
"hl": "true",
"fq": "",
"version": "2.2",
"rows": "10"
}
},
"response": {
"numFound": 1,
"start": 0,
"docs": [
{
"ekonr_tlc": "1030860",
"region_tlc": "NBST",
"ccZzcucbez_tlc": "GT EHG ERDINGER WEISSB.DKL.20X0,5L",
"id_tlc": "NBST_000000000135459003",
"gtin_tlc": "4002103010036"
}
]
},
"highlighting": {
"b2cLMIVProdukteIndex_NBST_000000000135459003": {
}
}
}
Try using this class structure:
class ResponseCall
{
[JsonProperty("responseHeader")]
public ResponseHeader ResponseHeader { get; set; }
[JsonProperty("response")]
public Response Response { get; set; }
[JsonProperty("highlighting")]
public Dictionary<string, object> Highlighting { get; set; }
}
class ResponseHeader
{
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("QTime")]
public int QTime { get; set; }
[JsonProperty("params")]
public Dictionary<string, string> Params { get; set; }
}
class Response
{
[JsonProperty("numFound")]
public int NumFound { get; set; }
[JsonProperty("start")]
public int Start { get; set; }
[JsonProperty("docs")]
public List<Dictionary<string, string>> Docs { get; set; }
}
Then deserialize like this:
ResponseCall rc = JsonConvert.DeserializeObject<ResponseCall>(json);
Fiddle: https://dotnetfiddle.net/FdQu7U

Deserializing a Json list of objects c#

ok so im not entirely sure how to explain this but ill give it my best shot. i have deserialisation from json working on singular objects, but when i get a list of the objects in json form, it doesnt work, and there are a few extra details outside of the singular objects when in a list of the objects.
the line of code im pretty sure is the problem is
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(JObject.Parse(json).ToString());
but i cannot figure out how to solve it.
anyway.
this is where the multiple data objects in json from come from:
public static async Task<DeserializedObjects.BlockList> GetUpToTenBlocks(int height)
{
var JData = (dynamic)new JObject();
JData.height = height;
String uri = String.Concat(partialApi, "/local/chain/blocks-after");
var response = await client.PostAsync(uri, new StringContent(JData.ToString(), Encoding.UTF8, "application/json"));
var content = response.Content;
{
var json = await content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(JObject.Parse(json).ToString());
Console.WriteLine(model.AtIndex[1].difficulty);
return model;
}
}
which is deserialized to:
public class PrevBlockHash
{
public string data { get; set; }
}
public class Block
{
public int timeStamp { get; set; }
public string signature { get; set; }
public PrevBlockHash prevBlockHash { get; set; }
public int type { get; set; }
public List<object> transactions { get; set; }
public int version { get; set; }
public string signer { get; set; }
public long height { get; set; }
}
public class Datum
{
public object difficulty { get; set; }
public List<object> txes { get; set; }
public Block block { get; set; }
public string hash { get; set; }
}
public class BlockList
{
public List<Datum> AtIndex { get; set; }
}
and this is the json payload:
{
"data": [
{
"difficulty": 11763927507942,
"txes": [],
"block": {
"timeStamp": 167479,
"signature": "bb062d9b5f132b39b9e56de2413bf04928af009587446621da7afd351d
15a2ce7b5504450acf41bc3b19ab71e9bf34722005239d93f05a2318130f85118df40c",
"prevBlockHash": {
"data": "d4875ad2fc74dacfa89a13f24159d14555d3766f4fe2d708a7596f84eba88
31b"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "00a30788dc1f042da959309639a884d8f6a87086cda10300d2a7c3a0e0891
a4d",
"height": 1001
},
"hash": "f70898011d7343a0823de9c9cf263de29ddf2c16bb78cea626b9af90ea7ec260"
},
{
"difficulty": 11625594628802,
"txes": [],
"block": {
"timeStamp": 167561,
"signature": "116dedf43dd06b9ca634db0e20e06cc93337cdba155bced4d843ece4cc
9a57487d58e9a34d8a0e19bf71d3b7facb15179a87767f0063ebbce7c940cd545d5f01",
"prevBlockHash": {
"data": "f70898011d7343a0823de9c9cf263de29ddf2c16bb78cea626b9af90ea7ec
260"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "6ecd181da287c9ccb0075336de36427f25cbc216dc6b1f0e87e35e41a39f6
3fe",
"height": 1002
},
"hash": "77b5644c35e0d0d51f8bb967d0d92e0ddb03c4ede6632cb3b7651b7394617562"
},
{
"difficulty": 11538802895169,
"txes": [],
"block": {
"timeStamp": 167624,
"signature": "982574132fdc99b6f484acdd3f1cb5229b2bf78ad7b4e9af3d7a1873da
b987401f8bf808ff749aca70c503f490db1411b6cd89dbb0c1daa24fd580f91d3d9601",
"prevBlockHash": {
"data": "77b5644c35e0d0d51f8bb967d0d92e0ddb03c4ede6632cb3b7651b7394617
562"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "26a3ac4b24647c77dc87780a95e50cb8d7744966e4569e3ac24e52c532c0c
d0d",
"height": 1003
},
"hash": "1a6d52c6317150d1839790da2c1481d714038c869842f769affbec0fdeec9861"
}
]
}
Try this:
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(json);
Console.WriteLine(model.data[1].difficulty);
along with, also:
public class BlockList
{
public List<Datum> data { get; set; }
}

Categories

Resources