Deserialize nested JSON array in C# - c#

I have a JSON array with nested objects, representing a menu, as this:
[
[
{
"name": "Item 1",
"id": 1
},
{
"name": "Item 2",
"id": 2,
"children": [
[
{
"name": "Item 21",
"id": 21
}
]
]
},
{
"name": "Item 3",
"id": 3,
"children": [
[
{
"name": "Item 31",
"id": 31,
"children": [
[
{
"name": "Item 311",
"id": 311
},
{
"name": "Item 312",
"id": 312
}
]
]
},
{
"name": "Item 32",
"id": 32
},
...
And I want to deserialize it using JavaScriptSerializer. I have some code as shown below but is not working.
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu>(jsonData);
...
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu[] children { get; set; }
}
The error I get is "The type 'Menu' is not supported to deserialize a matrix".
I would appreciate any help on how to declare the custom object.
Cheers.

Your root object is a 2d jagged array of objects. The properties "children" are also 2d jagged arrays. Thus your Menu class needs to be:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu [][] children { get; set; }
}
And deserialize your JSON as follows:
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu [][]>(jsonData);
Alternatively, if you prefer lists to arrays, do:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public List<List<Menu>> children { get; set; }
}
And then
var objects = serializer.Deserialize<List<List<Menu>>>(jsonData);

Could the issue be that the actual data is an array but you're telling it to expect just one Menu?

Related

Add item to JSON array section in C#

{
"name": "Not Okay Bears Solana #1",
"image": "ipfs://QmV7QPwmfc6iFXw2anb9oPZbkFR75zrtw6exd8LherHgvU/1.png",
"attributes": [
{
"trait_type": "Background",
"value": "Amethyst"
},
{
"trait_type": "Fur",
"value": "Warm Ivory"
},
{
"trait_type": "Mouth",
"value": "Clean Smile"
},
{
"trait_type": "Eyes",
"value": "Not Okay"
},
{
"trait_type": "Hat",
"value": "Bucket Hat"
},
{
"trait_type": "Clothes",
"value": "Plaid Jacket"
},
{
"trait_type": "Eyewear",
"value": "Plastic Glasses"
}
],
"description": "Not Okay Bears Solana is an NFT project for mental health awareness. 10k collection on the Polygon blockchain. We are not okay."
}
I need to add an object to attributes.
How to do this?
My JSON classes:
public class Attribute
{
public string trait_type { get; set; }
public string value { get; set; }
}
public class Root
{
public string name { get; set; }
public string image { get; set; }
public List<Attribute> attributes { get; set; }
public string description { get; set; }
}
try this, in this case you don't need any classes
var jsonObject = JObject.Parse(json);
JObject obj = new JObject();
obj.Add("trait_type", "type");
obj.Add("value", "value");
((JArray)jsonObject["attributes"]).Add(obj);
var newJson=jsonObject.ToString();
but if you need the data not a json , you can use this code
Root data = JsonConvert.DeserializeObject<Root>(json);
data.attributes.Add(new Attribute { trait_type="type", value="value"});

How to serialize a json string of this type in C# class object? [duplicate]

I have this JSON:
[
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 1",
"Values": [
"Acc 1"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "1",
"Values": [
"1"
]
}
}
],
"Name": "account",
"Id": "1"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 2",
"Values": [
"Acc 2"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "2",
"Values": [
"2"
]
}
}
],
"Name": "account",
"Id": "2"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 3",
"Values": [
"Acc 3"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "3",
"Values": [
"3"
]
}
}
],
"Name": "account",
"Id": "2"
}
]
And I have these classes:
public class RetrieveMultipleResponse
{
public List<Attribute> Attributes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Value
{
[JsonProperty("Value")]
public string value { get; set; }
public List<string> Values { get; set; }
}
public class Attribute
{
public string Key { get; set; }
public Value Value { get; set; }
}
I am trying to deserialize the above JSON using the code below:
var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);
but I am getting this error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'test.Model.RetrieveMultipleResponse' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly. To fix this
error either change the JSON to a JSON object (e.g. {"name":"value"})
or change the deserialized type to an array or a type that implements
a collection interface (e.g. ICollection, IList) like List that can
be deserialized from a JSON array. JsonArrayAttribute can also be
added to the type to force it to deserialize from a JSON array. Path
'', line 1, position 1.
Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
If one wants to support Generics (in an extension method) this is the pattern...
public static List<T> Deserialize<T>(this string SerializedJSONString)
{
var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
return stuff;
}
It is used like this:
var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();
MyClassType looks like this (must match name value pairs of JSON array)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyClassType
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "Manager")]
public string Manager { get; set; }
[JsonProperty(PropertyName = "LastUpdate")]
public DateTime LastUpdate { get; set; }
}
Use NUGET to download Newtonsoft.Json add a reference where needed...
using Newtonsoft.Json;
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
Deserializing JSON array into strongly typed .NET object
Use this, FrontData is JSON string:
var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);
and extract list:
var a = objResponse1[0];
var b = a.CustomerData;
To extract the first element (Key) try this method and it will be the same for the others :
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("Your URL"))
{
var apiResponse = await response.Content.ReadAsStringAsync();
var list = JObject.Parse(apiResponse)["Attributes"].Select(el => new { Key= (string)el["Key"] }).ToList();
var Keys= list.Select(p => p.Key).ToList();
}
}
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!

Cannot convert json to object

Hello i've got this error Message
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ClassLibraryMifosX.ViewModels.Rootobject2' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JS
my deserialize code :
Rootobject Rsc = JsonConvert.DeserializeObject<Rootobject>(json);
my class with json object description:
public class Rootobject
{
public List<Class1> Property1 { get; set; }
}
public class Class1
{
public int entityId { get; set; }
public string entityAccountNo { get; set; }
public string entityExternalId { get; set; }
public string entityName { get; set; }
public string entityType { get; set; }
public int parentId { get; set; }
public string parentName { get; set; }
public string entityMobileNo { get; set; }
public Entitystatus entityStatus { get; set; }
}
public class Entitystatus
{
public int id { get; set; }
public string code { get; set; }
public string value { get; set; }
}
my json :
[
{
"entityId": 1,
"entityAccountNo": "000000001",
"entityExternalId": "100001-241563",
"entityName": "Smith W R",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityMobileNo": "254728000000",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 310,
"entityAccountNo": "000000310",
"entityName": "John Smith",
"entityType": "CLIENT",
"parentId": 14,
"parentName": "TestOffice1",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 422,
"entityAccountNo": "000000422",
"entityExternalId": "smith1",
"entityName": "Smith Jones",
"entityType": "CLIENT",
"parentId": 11,
"parentName": "Barquisimeto",
"entityMobileNo": "88989898",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 774,
"entityAccountNo": "000000774",
"entityName": "John AAA Smith",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 1789,
"entityAccountNo": "Head Office000001789",
"entityExternalId": "547222",
"entityName": "Kaitlin Smith",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
}
]
what i have been done wrongly ? Thanks
There is no root object into your Json data so just deserialize it as a collection of Class1 like below:
var collection = JsonConvert.DeserializeObject<List<Class1>>(json);
Don't forget that VS can create for you a class that can be used to deserailize your Json data. You don't need to write yourself the definition of Class1. Just go to menu => Edit > Paste Special > Paste JSON as classes
The first and last character of your JSON is a square bracket [ ] rather than a curly bracket { }. This means that it is an array, not an object. In order to parse it, you need to deserialize it into an array of Class1 objects:
Class1[] Rsc = JsonConvert.DeserializeObject<Class1[]>(json);
If you wanted to use a Rootobject object instead, you could then use it like so:
Rootobject root = new RootObject();
root.Property1 = new List<Class1>(Rsc);

JSON Error converting value to type

It gives me error when deserializing this JSON File
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
I have the following classes for this JSON
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
What seems to be the problem? i'm deserializing this using
string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
and the exact error is
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
Im trying to get the value of "Id", What could be the problem with my code?
Your deserialization code should be:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
You're trying to deserialize it into a dictionary of string,Root, when the object itself is simply Root.
It does not seem to apply to your scenario, but note that when you do have JSON that is an array (root level children are array items, not properties), you may have to change the root object to subclass a compatible type.
For example:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
For people that this does not help, and that are not using Entity Framework and or writing the domain classes by hand - make sure all your class properties match what is coming out of your data source in the same exact field order.

How to deserialize JSON objects to List<> when the items are not in a Json array? (C#)

I'm using a Json string from another system. It looks something like this:
{
"BoolValue": true,
"Inventory": {
"Item1": {
"id": "1",
"name": "Item One"
},
"Item2": {
"id": "2",
"name": "Item Two"
},
"Item3": {
"id": "2",
"name": "Item Three"
}
}
}
How would I deserialize the "Item" objects to a List?
I know it's easy then the json uses an array for "Inventory": [] but how will I do it when it's just object after object under the Inventory property?
If I'm understanding correctly, you'll need a class setup like this:
public class Results {
public bool BoolValue { get; set; }
public Dictionary<string, Item> Inventory { get; set; }
}
public class Item {
public string id { get; set; }
public string name { get; set; }
}

Categories

Resources