How to convert json with jarray inside to a object

214 views Asked by At

I have the following classes

public class Test
{
    public string name;

    public List<Field> fields;
}

public class Field
{
    public string id;

    public string name;
}

and the following Json

{
    "name": "name1",
    "fields": [
    {
       "id": "4786182461",
       "name": "field1",
    },
    {
       "id": "41241241122",
       "name": "field2",
    },
    ]
}

I'm trying to convert this json to the Test object, the following code convert properly the "name", but the "fields" always returns null.

Test returnTest = JObject.Parse(json).ToObject<Test>()

Any ideas about how I can make the "fields" return the array?

1

There are 1 answers

0
Erik Philips On BEST ANSWER

The following works DotNetFiddle Example:

public static void Main()
{
    var json = "{\"name\": \"name1\",\"fields\": [{\"id\": \"4786182461\",\"name\": \"field1\",},{\"id\": \"41241241122\",\"name\": \"field2\",}, ]}";
    
    var result = JsonConvert.DeserializeObject<Test>(json);
    
    Console.WriteLine(result.Name);
    Console.WriteLine(result.Count);
}

public class Test
{
    public string Name;
    
    public List<Field> Fields;
}

public class Field
{
    public string id;
    public string name;
}

Result:

name1

2

However, I'd highly recommend you stick with best practices and use properties, for example:

public class Test
{
    public string Name { get; set; }
    
    public List<Field> Fields { get; set; }
}