1

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);
2
  • 1
    It's because the data property is not of Dictionary type rather it's of type FindResponseData which in turn having a Dictionary property with name sku. So when Serializer tries to map the data property from the json, it will look for a value which should be an object with a property sku which can be further mapped as dictionary. In that case, the json should be something like { "status": "success", "data": {"sku":{ "01234": { "001": "20", "123": "10" }, "56789": { "001": "100", "328": "5" } } }}. Commented Mar 2, 2017 at 17:42
  • @SivaramK Thanks for the explanation. Commented Mar 2, 2017 at 21:09

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

It would be more convenient using Hashtable instead of Dictionaries.
@sivaram-k thanks. That worked. I updated the question to include what I was initially trying, which wasn't working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.