Home > Back-end >  DeserializeObject<Dictionary<string, object> JSON string
DeserializeObject<Dictionary<string, object> JSON string

Time:06-10

I have this JSON request

{
  "status": "completed",
  "test":"hi",
  "order":{
      "name":"book",
      "qty":"2"
  },
  "customer":{
    "name":"sajid",
    "address":"salmiya"
  },
  "products":{
    "name":"abc",
    "qty":"1"
  }
}

I have already Deserialized JSON using this

Dictionary<string, object> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(test);

But I am unable to get the values of product name and quantity and similar way I want the values for customer.

CodePudding user response:

In your dictionay a key is a string type, but a value is JObject. To get data you have to cast a dictionary value to JObject

Dictionary<string, object> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(test);

Dictionary<string,string> products =((JObject) values["products"]).ToObject<Dictionary<string,string>>();

//or
var products = (JObject) values["products"];

var productName= products["name"];
var productQty = products["qty"];

// or directly

productName= (string) ((JObject) values["products"])["name"];
productQty = (string) ((JObject) values["products"])["qty"];
  • Related