Search code examples
c#json.netjson-deserialization

Parse JSON into class without JsonProperty


Example data:

{
  "status": "success",
  "data": {
    "01234": {
      "001": "20",
      "123": "10"
    },
    "56789": {
      "001": "100",
      "328": "5"
    }
  }
}

I would like to check to make sure the "status" = "success" and if so, then flatten the "data" into more of a relational structure to store in a relational database. From the above it would look something like:

Product Location  Quantity
01234   001       20
01234   123       10
56789   001       100
56789   328       5

My understanding is since the "01234" and "56789" are going to change I'm not going to be able to create a class to deserialize into using a JsonProperty.

How do I go about deserializing this into a class? Would it be easier to just deserialize without using a class?

Edit

I was able to get it to work based on the accepted answer, but am wondering why this doesn't work (it's what I was trying before posting this question):

public class FindResponse { 
    [JsonProperty("status")] 
    public string status { get; set; } 
    [JsonProperty("data")] 
    public FindResponseData data { get; set; } 
} 

public class FindResponseData { 
    public Dictionary<string, Dictionary<string, int>> sku { get; set; } 
} 

//This doesn't work; the "data" in the "result" object was null. 
var result = JsonConvert.DeserializeObject<FindResponse>(skusJson);

Solution

  • You could create a class as below and try to map the data using the dictionary values after deserialization. May not be the better approach but it will suit your data model.

    public class MyClass {
            public string Status { get; set; }
            public Dictionary<string, Dictionary<string, string>> Data { get; set; }
        }
    
       //and then
       var data = JsonConvert.DeserializeObject<MyClass>(jsonContent);