I have two string values in a JSON object. I want to call this method in same class and use the values without using class.
I am using the following method:
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
I need to use this data and result value in another method.
I am getting the value like:
var Details = JsonConvert.SerializeObject(Details());
My output is:
{
\"ContentEncoding\": null,
\"ContentType\": null,
\"Data\": {
\"Data\": \"DisplayName\",
\"result\": \"UniqueName\"
},
\"JsonRequestBehavior\": 1,
\"MaxJsonLength\": null,
\"RecursionLimit\": null
}
How do I get the data and result value from this?
The method which you are using (i.e:)
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
returns a JsonResult
object which has a property named Data
, i.e Details().Data
, which contains the data your object contains. So in order to get your object's Data
and result
values, you need to serialize it again.
This is the full solution:
JsonResult json = Details(); // returns JsonResult type object
string ser = JsonConvert.SerializeObject(json.Data); // serializing JsonResult object (it will give you json string)
object dec = JsonConvert.DeserializeObject(ser); // deserializing Json string (it will deserialize Json string)
JObject obj = JObject.Parse(dec.ToString()); // it will parse deserialize Json object
string name = obj["Data"].ToString(); // now after parsing deserialize Json object you can get individual values by key i.e.
string name = obj["Data"].ToString(); // will give Data value
string name = obj["result"].ToString(); // will give result value
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With