Home > Back-end >  Deserializing a json array into a object C# using System.Text.Json
Deserializing a json array into a object C# using System.Text.Json

Time:05-26

I have some JSON returning from an API that is in the form of

[
    {
        "param1":"value",
        "param2":"value2",
        ...
    },
    {
        "param1":"value",
        "param2":"value2",
         ...
    }
]

I have a class Foo:

public class Foo
{
    public string param1 { get; set; }
    public string param2 { get; set; }
}

I am using the System.Text.Json library.

If I deserialize like this:

var output = JsonSerializer.Deserialize<List<Foo>>(JsonStr)

all works fine and in 'output' I have a list of Foo.

However, I want to deserialize into another class so I can do some inheritance from a base class that can perform some checks to see if there is data and some other bits and bobs.

public class Bar : BarBase
{
    public List<Foo> data { get; set; }
}

Obviously, if I try to deserialize into Bar, it throws an error that it cannot map the JSON to the object.

Is there any attribute that can be used to state that the JSON should map to 'data' or is there a different way to go about this?

Cheers Mark

CodePudding user response:

The issue can be solved by letting the Bar class inherit from List

public class Bar : List<Foo>
{
  public List<Foo> data { get; set; }
}
  • Related