Home > Net >  Convert array of key objects pair to a C# object
Convert array of key objects pair to a C# object

Time:12-15

I have a api that return data in this format

 [
  "70": {
    "type_id": 3,
    "type": "forex",
    "group_title": "forex",
    "name": "EUR",
    "title": "EUR"
  },
  "724": {
    "type_id": 5,
    "type": "shares",
    "group_title": "shares",
    "name": "#ABT",
    "title": "#ABT"
  }
]

Now I want these key object pair data to a genuine C# object array. Like this

 [
  {
    Id = 70
    Type_id = 3,
    Type = "forex",
    Group_title = "forex",
    Name = "EUR",
    Title = "EUR"
  },
  {
    Id = 724,
    Type_id = 5,
    Type = "shares",
    Group_title = "shares",
    Name = "#ABT",
    Title = "#ABT"
  }
]

Is it possible to do so?

CodePudding user response:

create class with those properties then use below code:

JsonSerializer.Deserialize<List<object>>(jsonString);

here is link to more detail:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0

CodePudding user response:

Say you have some classes:

public class Root
{
    [JsonProperty("result")]
    public Dictionary<int, Data> Result {get;set;}
}

public class Data
{
    [JsonIgnore]
    public int Id { get; set; }

    [JsonProperty("type_id")]
    public int TypeId { get; set; }

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

    [JsonProperty("group_title")]
    public string GroupTitle { get; set; }

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

    [JsonProperty("title")]
    public string Title { get; set; }
}

You can deser the original data (not the one you modified by removing "result") and then call, if you want an array out of it:

var root = JsonConvert.DeserializeObject<Root>(str);
foreach(var kvp in root) kvp.Value.Id = kvp.Key;
var arr = root.Values.ToArray();
  • Related