I am trying to parse a bunch of XML files into a single JSON file, which is already working.
The final JSON file looks like the following:
{
"items": [
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
},
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
...
Instead, I want to achieve the following structure:
{
"items": [
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
],
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
]
}
But I don't know how to define my objects in order to do so, my current structure is as follows:
public class Items
{
public List<Item> items;
}
public class Item
{
public List<SubItem> subItems;
}
public class SubItem
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
How should I do this?
The answer is simple: turn your objects into lists: This will remove the prop names (and object notation in json).
public class Items
{
public List<Item> items; //list with prop name 'items'
}
public class Item : List<SubItem> // list in list like json notation
{
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
As #FlilipCordas noted Inheriting from list is bad practice (for good reason)
you are better of this way:
public class Items
{
public List<List<SubItem>> items; //list with list with prop name 'items'
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
Copy your json then go in Visual Studio.
Click on "Edit" > "Paste Special" > "Paste JSON as Classes"
All the classes are automatically created. I hope this tip could help you.
Related
{
"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"});
I'm trying to find an elegant way in C# using System.Text.Json to deserialize a list of objects that were serialized (from C++ with cereal) with the following JSON data:
{
"value":
[
{
"ptr_wrapper": {
"id": 2147483649,
"data": {
"cereal_class_version": 6,
"ID": 1,
"name": "CWC",
"shadowCompetition": {
"ptr_wrapper": {
"id": 0
}
},
"userPlayable": true
}
}
},
{
"ptr_wrapper": {
"id": 2147483650,
"data": {
"ID": 20,
"name": "NAME2",
"shadowCompetition": {
"ptr_wrapper": {
"id": 0
}
},
"userPlayable": true
}
}
}
]
}
and deserialize this into a list for the following class:
class Competition
{
public int ID { get; set; }
public string name { get; set; }
public bool userPlayable { get; set; }
public Competition? shadowCompetition { get; set; }
}
I can skip the first node "value" easily. But then, the "ptr_wrapper" node encapsulates the "data" node that contains the data I really want to get.
I believe that a JsonConverter may be the answer, but I'm really struggling to find a solution.
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!
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?
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; }
}