Reputation: 4124
how can I deserialize json arrays with newtonsoft?
Here my json file:
{
"one": [
{
"one":"1",
"two":"2",
"three":"3"
},
{
"one":"1",
"two":"2",
"three":"3"
}
],
"two": [
{
"one":"1",
"two":"2",
"three":"3"
}
]
}
Here is my code:
myList= JsonConvert.DeserializeObject <List<MyClass>>(jsonFile);
public class MyClass
{
public string one{ get; set; }
public string two { get; set; }
public string three { get; set; }
}
Maybe I need change in some way my json file?
Upvotes: 0
Views: 163
Reputation: 10091
You should deserialize it as a Dictionary<string, MyClass[]>
var test = "{ \"one\": [ { \"one\":\"1\", \"two\":\"2\", \"three\":\"3\" }, { \"one\":\"1\", \"two\":\"2\", \"three\":\"3\" } ], \"two\": [ { \"one\":\"1\", \"two\":\"2\", \"three\":\"3\" } ] }";
var testar = JsonConvert.DeserializeObject <Dictionary<string, MyClass[]>>(test);
This would work out of the box if there is more keys added like Forth, Fifth and so on.
Upvotes: 0
Reputation: 151730
That is no JSON array, it is an object with two array properties.
public class YourClass
{
public string one { get; set; }
public string two { get; set; }
public string three { get; set; }
}
public class RootObject
{
public List<YourClass> one { get; set; }
public List<YourClass> two { get; set; }
}
(Don't we still have a canonical question for this? Every day the same...)
Upvotes: 0
Reputation: 4178
If you want to keep your class structure you have to change your json file into this:
[
{
"one":"1",
"two":"2",
"three":"3"
},
{
"one":"1",
"two":"2",
"three":"3"
}
]
With this json file style the deserialization
myList= JsonConvert.DeserializeObject <List<MyClass>>(jsonFile);
will complete properly.
Your above json file has two arrays in it. Because of that the deserialization will fail.
Upvotes: 0
Reputation: 166
Try This :
`public class Foo
{
[JsonProperty("one")]
public string One { get; set; }
[JsonProperty("two")]
public string Two { get; set; }
[JsonProperty("three")]
public string Three { get; set; }
}
public class RootObject
{
[JsonProperty("one")]
public List<Foo> One { get; set; }
[JsonProperty("two")]
public List<Foo> Two { get; set; }
}`
and to deserialize object use
` RootObject _rootObject = JsonConvert.DeserializeObject<RootObject>
(jObject.ToString());`
Upvotes: 0
Reputation: 149646
Your class needs to match the structure your JSON. It should look like this:
public class Foo
{
[JsonProperty("one")]
public string One { get; set; }
[JsonProperty("two")]
public string Two { get; set; }
[JsonProperty("three")]
public string Three { get; set; }
}
public class RootObject
{
[JsonProperty("one")]
public List<Foo> One { get; set; }
[JsonProperty("two")]
public List<Foo> Two { get; set; }
}
Now it will properly deserialize:
Console.WriteLine(JsonConvert.DeserializeObject<RootObject>(json));
Upvotes: 1