Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON object in C# without using class

Tags:

json

c#

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?

like image 539
Shesha Avatar asked Jan 06 '16 05:01

Shesha


1 Answers

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.

like image 119
Syed Muhammad Zeeshan Avatar answered Oct 21 '22 17:10

Syed Muhammad Zeeshan