I have a class in the format:
public class Person
{
public string Name {get;set;}
public int Age {get;set;}
public string Car {get;set;}
}
What i tried to read the JSON from a file:
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
//var items = JsonConvert.DeserializeObject<IEnumerable<Person>>(json);
}
When I got the JSON in a string I got that in the format below:
[
["John", 30, "BMW"],
["Tim", 45, "Ford"],
["Kim", 34, "Toyota"]
]
I thought that JSON would be Deserialize in that IEnumerable<Person>
, but it couldn't.
What is the correct way to deserialize the JSON string with that Person
class?
Since you have only values without properties names in your JSON, you can deserialize it into sequence of collection objects, like IEnumerable<string[]>
, IEnumerable<List<string>>
or List<List<string>>
. Then parse every item to Person
manually (assuming that you have the same structure for all items, otherwise you'll need an additional logic for checking an errors)
var result = JsonConvert.DeserializeObject<IEnumerable<string[]>>(jsonString);
var persons = result
.Select(item => new Person { Name = item[0], Age = int.Parse(item[1]), Car = item[2] })
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With