rtshmittl
rtshmittl

Reputation: 64

Parsing JSON data in C#

I have a JSON data as follows

 {"id": "367501354973","from": {
  "name": "Bret Taylor",
  "id": "220439"   }

which is returned by an object(result) of IDictionary[String, Object]

In my C# code:

I have made a class for storing the JSON value which is as follows

public class SContent
{
    public string id { get; set; }
    public string from_name { get; set; }
    public string from_id { get; set; }
}

My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:

List<object> data = (List<object>)result["data"];
            foreach (IDictionary<string, object> content in data)
            {
                SContent s = new SContent();

                    s.id = (string)content["id"];
                    s.from_name = (string)content["from.name"];
                    s.from_id = (string)content["from.id"];

            }

When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"

When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.

I think i am not able to refer the nested JSON data properly.

Can anyone just validate it and please tell me how to refer nested data in JSON in C#?

Thanks

Upvotes: 0

Views: 9152

Answers (1)

drwatsoncode
drwatsoncode

Reputation: 5223

I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?

You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)

Using that class, you would write your code like this:

public class SContent
{
    public string id { get; set; }
    public SFrom from { get; set; }
}

public class SFrom 
{
    public string name { get; set; }
    public string id { get; set; }
}

Then deserialization looks like this:

var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);

See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Upvotes: 5

Related Questions