I have JSON file like:
[
12,
[
{
"id": "131",
"name": "Cate"
},
{
"id": "132",
"name": "Mike"
}
],
"Result OK"
]
And Code:
private static void Main(string[] args)
{
using (var r = new StreamReader(@"C:\Path\data1.json"))
{
var json = r.ReadToEnd();
try
{
var items = JsonConvert.DeserializeObject<JsonBody>(json);
Console.WriteLine(items);
}
catch (JsonSerializationException ex)
{
Console.WriteLine(ex);
}
}
}
public class JsonBody
{
public int someint;
public List<Dictionary<string, Item>> item;
public string somestring;
}
public class Item
{
[JsonProperty("id")] public string id;
[JsonProperty("name")] public string name;
}
Error:Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Json_parser.Parse2+JsonBody' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
What should be rewritten in the code to avoid this error. How do I parse this JSON correctly? I need to get all items from the Item class.
Since the root of your JSON document is a list, you need to deserialize it into a collection type in C# using Json.Net. Unfortunately, this kind of data structure with mixed element types is a bit hard to consume.
If you know 100% that the root of the document will always be an array, you can deserialize it like this:
JArray root = JArray.Parse(json);
Then, if you know 100% that the 2nd element of this array will be the nested array of items you're interested in you can use this:
Item[] items = root[1].ToObject<Item[]>();
So your method could be simplified to:
string json = File.ReadAllText(@"C:\Path\data1.json");
JArray root = JArray.Parse(json);
Item[] items = root[1].ToObject<Item[]>();
However, if you need to hunt for the nested array, in that it will not always be the 2nd element, you can use this:
string json = File.ReadAllText(@"C:\Path\data1.json");
JArray root = JArray.Parse(json);
foreach (var element in root)
if (element is JArray)
{
Item[] items = element.ToObject<Item[]>();
// ...
}