How to deserialize a collection with a collection with Newtonsoft.json?

Viewed 258

I have some Json content that contains an array, where each item contains an array of objects. I'm searching for a way to convert this into a list of objects. It is only the object with id and biCode is what I'm after, their parent is of no importance for me I tried the https://json2csharp.com/ website, but according to the output I need to create a Class for each parent object ("UselessText1", "UselessText2", etc) and they just contain id and biCode. I tried to use it, but (as I would have guessed) it didn't work

It threw this Exception: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Root]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

This is the json:

{
"UselessText1": [],
"UselessText2": [
    {
        "id": 2,
        "biCode": "Something useful"
    }
],
"UselessText3": [
    {
        "id": 3,
        "biCode": "Something useful"
    },
    {
        "id": 4,
        "biCode": "Something useful"
    }
]}

Any idea how to deserialize this? Any Google result I found didn't show a situation like mine. I probably didn't know exactly what to search for

2 Answers

try this

var json=...your json string

var deseializedJson = JsonConvert.DeserializeObject< Dictionary<string,UselessText[]>>(json);

var output = JsonConvert.SerializeObject(deseializedJson);

   public class UselessText
    {
        public int id { get; set; }
        public string biCode { get; set; }
    }

output

{"UselessText1":[],
"UselessText2":[{"id":2,"biCode":"Something useful"}],
"UselessText3":[{"id":3,"biCode":"Something useful"},{"id":4,"biCode":"Something useful"}]}

Your Json example is a little bit weird. It looks like you have an object that contains multiple properties of the same type.

Something that should work for this exact Json would be:

public class MyModel{
    public IEnumerable<MyEntity> UselessText1;
    public IEnumerable<MyEntity> UselessText2;
    public IEnumerable<MyEntity> UselessText3;
}

public class MyEntity{
    public int Id;
    public string BiCode;
}
Related