Reputation: 35
I am trying to deserialize the following:
[
{
"items":[
{
"b":1,
"Q":"data"
},
{
"b":2,
"Q":"more data"
}
]
},
{
"seconds_ago":1
}
]
I try to deserialize into a C# object using
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Item[] items { get; set; }
public int seconds_ago { get; set; }
}
public class Item
{
public int b { get; set; }
public string Q { get; set; }
}
public void test()
{
Rootobject deserializedObject = JsonConvert.DeserializeObject<Rootobject>(json);
}
But i throws out various errors regardless of what i try, obvious user error.
Can anyone throw me in the right direction on how to parse the example above using JSON.net?
Upvotes: 2
Views: 220
Reputation: 2984
I wonder where you got the Json from, or you just came up with it by yourself. It's not really optimal Json to work with, but since this is your example I'l show you how to deserialize it with a mapping model.
Correct classes (for the Json you provided) to do the mapping on will look like these::
public class Item
{
public int b { get; set; }
public string Q { get; set; }
}
public class Rootobject
{
public List<Item> items { get; set; }
public int? seconds_ago { get; set; }
}
To deserialize it you use List<Rootobject>
as the type, since there is more then one root object (because it's an array) []
:
List<Rootobject> deserializedList = JsonConvert.DeserializeObject<List<Rootobject>>(json);
Upvotes: 3
Reputation: 1085
here is your solution:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var data = @"{
'Property1': [{
'items': [{
'b': 1,
'Q': 'data'
}, {
'b': 2,
'Q': 'more data'
}],
'seconds_ago': 1
}]
}";
Rootobject deserializedObject = JsonConvert.DeserializeObject<Rootobject>(data);
Console.WriteLine(deserializedObject.Property1[0].items[0].b);
Console.WriteLine(deserializedObject.Property1[0].items[0].Q);
Console.WriteLine(deserializedObject.Property1[0].items[1].b);
Console.WriteLine(deserializedObject.Property1[0].items[1].Q);
Console.WriteLine(deserializedObject.Property1[0].seconds_ago);
}
}
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Item[] items { get; set; }
public int seconds_ago { get; set; }
}
public class Item
{
public int b { get; set; }
public string Q { get; set; }
}
You can try it here: https://dotnetfiddle.net/33ZPyX
Problem is mainly structure of your json and your objects. They don't match. Have a look on that fiddle and you should see why.
Upvotes: -2