-1

I'm working with an API that returns a JSON that has a key which is "unique". As you can see there is PRODUCT_1, PRODUCT_2, PRODUCT_3 and the list would go on.

{
"success": true,
"lastUpdated": 1657211399332,
"products": {
    "PRODUCT_1": {
        "product_id": "PRODUCT_1",
        "sell_summary": [],
        "buy_summary": [],
        "quick_status": {}
    },
    "PRODUCT_2": {
        "product_id": "PRODUCT_2",
        "sell_summary": [],
        "buy_summary": [],
        "quick_status": {}
    },
    "PRODUCT_3": {
        "product_id": "PRODUCT_3",
        "sell_summary": [],
        "buy_summary": [],
        "quick_status": {}
    }
}

I'm using the Newtonsoft.Json package but I can't figure out how to make it work.


EDIT:

With StriplingWarrior's comment ("Most likely you want to make the products property a Dictionary<string, Product>.") I could fix my code.

I replaced public Products[] products { get; set; } with public Dictionary<string, Product> products { get; set; } and it works fine.

Thanks for the help!

vrexon
  • 9
  • 3

1 Answers1

2

Try this

var productsObj = (JObject)JObject.Parse(json)["products"];

List<Product> products = productsObj.Properties()
    .Select(o => o.Value.ToObject<Product>())
    .ToList();

public partial class Product
{
    [JsonProperty("product_id")]
    public string ProductId { get; set; }

    [JsonProperty("sell_summary")]
    public List<object> SellSummary { get; set; }

    [JsonProperty("buy_summary")]
    public List<object> BuySummary { get; set; }

    [JsonProperty("quick_status")]
    public object QuickStatus { get; set; }
}
James Gould
  • 4,492
  • 2
  • 27
  • 50
Serge
  • 40,935
  • 4
  • 18
  • 45