Home > Software engineering >  How to setup json deserizlization from Object to Array in C#
How to setup json deserizlization from Object to Array in C#

Time:06-21

I got this strange API response from external service:

{
    "Columns": {
      "1": {
        "Fuels": [
          "1",
          "10",
          "4",
          "4"
        ]
      },
...
      "6": {
        "Fuels": [
          "1",
          "4",
          "10"
        ]
      }
    }
}

By default, all converters (json -> to csharp model) does models like this:

public class _1
{
    public List<string> Fuels { get; set; }
}

public class _2
{
    public List<string> Fuels { get; set; }
}

public class _3
{
    public List<string> Fuels { get; set; }
}

public class _4
{
    public List<string> Fuels { get; set; }
}

public class Columns
{
    public _1 _1 { get; set; }
    public _2 _2 { get; set; }
    public _3 _3 { get; set; }
    public _4 _4 { get; set; }
}

But I want something like this:

public class Column
{
    public string Number { get; set; }
    public List<string> Fuels { get; set; }
}

I think it's a side developers fault with Json serialization, because Columns should be an Array, but it's an Objects :(

I need to somehow convert this to Array, maybe it is some Newtonsoft or default .NET Json converter attributes or something to do that without writing custom deserializer?
I'm using .NET 6.

CodePudding user response:

Json.Net can deserialize any object into a Dictionary<string, object>.

You can specialise the key's and value's types, in your case:

  • int
  • Column

Where Column is defined as

public class Column
{
   public List<string> Fuels {get; set;}
}

So, if you define your Columns property in your root class as Dictionary<int, Column> then it will work fine with the default json converter

public class Root
{
   public Dictionary<int, Column> Columns;
}

Imperative usage:

var result = JsonConvert.DeserializeObject<Root>(json).Columns;

CodePudding user response:

try this

List<Column> columns = ((JObject)JObject.Parse(json)["Columns"]).Properties()
                    .Select(v => new Column(v.Name, v.Value["Fuels"].ToObject<List<string>>()))
                    .ToList();

class

public class Column
{
    public string Number { get; set; }
    private List<string> Fuels { get; set; }

    public Column(string number, List<string> fuels)

    {
        Number = number;
        Fuels = fuels;
    }
    public Column(){}
}

CodePudding user response:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class _1
{
    public List<string> Fuels { get; set; }
}

public class _6
{
    public List<string> Fuels { get; set; }
}

public class Columns
{
    public _1 _1 { get; set; }
    public _6 _6 { get; set; }
}

public class Root
{
    public Columns Columns { get; set; }
}
  • Related