Home > other >  Deserialize JSON object with generic class name
Deserialize JSON object with generic class name

Time:07-12

I try to deserialize object (have more data, but that's not the most important thing) like:

"object":{
            "type":"ABC",
            "year":2022,
            "authors":{
               "hh5as666asd66asd":{
                  "name":"Name",
                  "lastName":"LastName"
               }
          },

my problem is generic class name for authors list. Is any way to write generic class to grab data and desiarialize it correctly? Even if there will be more than 1 author?

public class Object
{
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("year")]
        public int Year { get; set; }

        [JsonProperty("authors")]
        public Authors Authors { get; set; }      
}

I use to deserialize:

var result = JsonConvert.DeserializeObject<MyClass>(response.Content);

CodePudding user response:

Yes, a generic class of json properties (key-value pairs) would be a dictionary.

Try someting like

public class Author
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("lastName")]
    public string LastName { get; set; }
}

public class Object
{
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("year")]
        public int Year { get; set; }

        [JsonProperty("authors")]
        public Dictionary<string, Author> Authors { get; set; }      
}

And deserialize it like you did.

CodePudding user response:

You can try dynamic:

var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
  • Related