Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON array of arrays into c# class [duplicate]

Tags:

json

c#

json.net

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?

like image 656
AkshayKriti Avatar asked Sep 05 '25 13:09

AkshayKriti


1 Answers

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();
like image 130
Pavel Anikhouski Avatar answered Sep 08 '25 12:09

Pavel Anikhouski