Michal
Michal

Reputation: 93

How to deserialize dynamically named JSON in c#?

I know there is a lot of similar questions and i tried to use it for last 12 h but without result. So please give me any advice how to solved my problem.

My json response look like this:

{
  "status": "OK",
  "products": {
    "dynamic10259668": {
      "ean": "4525348924",
      "sku": "9384573245",
      "name": "name1",
    },
    "dynamic10630436": {
      "ean": "983623203943",
      "sku": "9312763245",
      "name": "name2"
    },
    "dynamic10634396": {
     "ean": "1002904820",
     "sku": "9384763245",
     "name": "name3"
    },
    "dynamic10634398": {
      "ean": "3400901100",
      "sku": "9312763245",
      "name": "name4"
    },
    "dynamic10634399": {
      "ean": "8100103701",
      "sku": "454763245",
      "name": "name5"
    },
    "dynamic10634766": {
      "ean": "5600904820",
      "sku": "9384763245",
      "name": "name6"
    }
  }
}

And models:

public class ProductsList

{
    public string status { get; set; }
    public ListProducts products { get; set; }
}

public class ListProducts
{
    public ListProduct product { get; set; }
}

public class ListProduct
{
    public string ean { get; set; }
    public string sku { get; set; }
    public string name { get; set; }
}

Now i need e.g. Directory<"dynamic10259668", "9384573245"> but don't know how to access to product value. I have try this code:

ProductsList productsList = JsonConvert.DeserializeObject<ProductsList>(response.Content);

foreach (ListProduct singleProduct in productsList.products.product)
{
    Console.WriteLine(singleProduct.name);
}

My most common error is:

System.NullReferenceException: Object reference not set to an instance of an object.

Upvotes: 0

Views: 159

Answers (2)

Naylor
Naylor

Reputation: 903

It looks like you were hoping for a dictionary of product name to ean. If that is all you need then the following code would work:

dynamic d = JObject.Parse(response.Content);
var productDictionary = new Dictionary<string, string>();
foreach (var product in d.products)
{
   productDictionary[product.Name] = (string)product.Value.ean;
}

Upvotes: 1

Flydog57
Flydog57

Reputation: 7111

You need to use a Dictionary<string, ListProduct>. I believe that will do what you want.

I kept your ListProduct class, but modified ProductsList to look like this:

public class ProductsList
{
    public string status { get; set; }
    public Dictionary<string, ListProduct> products { get; set; }
}

When I do that, this code properly deserializes your JSON:

var result = JsonConvert.DeserializeObject<ProductsList>(theJson);

You can get to the data for dynamic10259668 using something like:

if (result.products.TryGetValue("dynamic10259668", out var item))
{
    Debug.WriteLine($"Name: {item.name}, Ean: {item.ean}, Sku: {item.sku}");
}

Upvotes: 2

Related Questions