I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
Related
I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
I am trying to use an RESTFUL API for an application we use internally. One call to the API returns the following JSON:
{
"operation": {
"name": "GET RESOURCES",
"result": {
"status": "Success",
"message": "Query was successful"
},
"totalRows": 2,
"Details": [{
"RESOURCE DESCRIPTION": "Windows",
"RESOURCE TYPE": "Windows",
"RESOURCE ID": "101",
"RESOURCE NAME": "WINDOWSPC",
"NOOFACCOUNTS": "1"
}, {
"RESOURCE DESCRIPTION": "Ubuntu",
"RESOURCE TYPE": "Linux",
"RESOURCE ID": "808",
"RESOURCE NAME": "UBUNTUPC",
"NOOFACCOUNTS": "2"
}]
}
}
Using json.net I deseralize the json and check the stats with the following lines:
dynamic json = JsonConvert.DeserializeObject(response);
var status = json.operation.result.status.Value;
Next I want to get each value of each of the "Details" returned, but I cannot figure out how. I first tried getting the Details only with this:
var resourceList = json.operation.Details
Which works, but I cannot iterate over this to get just the "RESOURCE ID" and "RESOURCE NAME" for example.
I cannot use .Children() either, but when I hover over the resourceList there is a ChildrenTokens which seems to be what I want, but I cannot get at that in my code.
I also tried using resourceList as a DataSet as per their example but it throws an exception.
Can someone see what I am doing wrong..... I am not familiar with parsing JSON in C#
You can use Json.Linq for that and parse a response into JObject, then iterate it foreach loop. It's possible, since Details is an array and JObject implements IDictionary<string, JToken> and IEnumerable<KeyValuePair<string, JToken>>
var jObject = JObject.Parse(response);
foreach (var detail in jObject["operation"]["Details"])
{
var description = detail["RESOURCE DESCRIPTION"].Value<string>();
//other properties
}
Here's an example using the JObject class instead of dynamic
JObject json = JObject.Parse(response);
string status = json["operation"]["result"]["status"].Value<string>();
foreach (JToken resource in json["operation"]["Details"])
{
string id = resource["RESOURCE ID"].Value<string>();
string name = resource["RESOURCE NAME"].Value<string>();
}
It is as simple as this:
Your Model classes would look like:
public class Result
{
public string status { get; set; }
public string message { get; set; }
}
public class Detail
{
[JsonProperty("RESOURCE DESCRIPTION")]
public string ResourceDescription { get; set; }
[JsonProperty("RESOURCE TYPE")]
public string ResourceType { get; set; }
[JsonProperty("RESOURCE ID")]
public string ResourceId { get; set; }
[JsonProperty("RESOURCE NAME")]
public string ResourceName { get; set; }
[JsonProperty("NOOFACCOUNTS")]
public string NoOfAccounts { get; set; }
}
public class Operation
{
public string name { get; set; }
public Result result { get; set; }
public int totalRows { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public Operation operation { get; set; }
}
To de-serialize:
var json = JsonConvert.DeserializeObject<RootObject>(response);
To access a property:
var name=json.operation.name
To access your Details:
foreach(var item in json.operation.Details)
{
var myresourcename=item.ResourceName;
//So on
}
I cannot read json string with c#. I getting error while reading.
Json file
{
"Invoice": {
"Description": "New",
"InvoiceTypeId": "3d166468-3923-11e6-9e7c-40e230cfb8ae",
"CustomerAccountsId": "TEST",
"InvoiceDate": "2016-06-27",
"PayableDate": "2016-06-27",
"Prefix": "A",
"Serial": "34222",
"tag": "TEST"
},
"InvoiceLine": [
{
"ValueId": "c41d3d85-3a1e-11e6-9e7c-40e230cfb8ae",
"Qantity": "3",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.500,00",
"VatRateId": "18",
"LineVat": "810,00",
"LineTotal": "5.310,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
},
{
"ValueId": "fd11b236-3952-11e6-9e7c-40e230cfb8ae",
"Qantity": "5",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.000,00",
"VatRateId": "18",
"LineVat": "900,00",
"LineTotal": "5.900,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
}
]
}
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
JArray jsonVal = JArray.Parse(jsonArr) as JArray;
dynamic vars = jsonVal;
But everything right, I do not see bugs.
Don't do this...you're parsing to an array when it's clearly a complex object.
Use a converter such as Visual Studio or json2csharp.com to create the appropriate target object structure:
public class Invoice
{
public string Description { get; set; }
public string InvoiceTypeId { get; set; }
public string CustomerAccountsId { get; set; }
public string InvoiceDate { get; set; }
public string PayableDate { get; set; }
public string Prefix { get; set; }
public string Serial { get; set; }
public string tag { get; set; }
}
public class InvoiceLine
{
public string ValueId { get; set; }
public string Qantity { get; set; }
public string UnitId { get; set; }
public string Price { get; set; }
public string VatRateId { get; set; }
public string LineVat { get; set; }
public string LineTotal { get; set; }
public string Vat { get; set; }
}
public class Invoices
{
public Invoice Invoice { get; set; }
public List<InvoiceLine> InvoiceLine { get; set; }
}
Then simply use the JsonConvert methods to deserialize.
var parsedJson = JsonConvert.DeserializeObject<Invoices>(json);
You can also deserialize it to a dynamic object. Of course this is not ideal but if you don't want to create a whole new type for it, this would work
var vars =JsonConvert.DeserializeObject<dynamic>( jsonArr);
//vars.InvoiceLine
I noticed in the question and a comment you made, "How do I read this?" that you might also be confused on reading JSON which made the error message confusing to you.
You are trying to parse the object as a JArray while your JSON isn't for an array.
If you look at your error message,
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
It's immediately throwing an error at the first character on the first line of your JSON and telling you it's not an array.
{ is the first character of your JSON, it was an array than it should start with [ just like if you were writing JavaScript.
Array:
var javaScriptArray = ["This", "Is", "An", "Array"];
Object:
var javaScriptObject = { id: 0, thisIsAnArray: false };
And put it together:
var javaScriptArrayOfObjects = [ { id: 0, thisIsAnArray: false},{ id: 1, thisIsAnArray: false} ];
You can see that when you look at your JSON (Java Script Object Notation) you should be able to tell if it's an array of objects or an object with arrays.
this should point you to it being a complex object and not an array and David L's answer covers that perfectly.
I just wanted to touch on better understanding the error message.
I just got my json response as a string.My json is given below,
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
Like hjeke and Second there are many key value pairs,how can i deserialize my json using Newtonsoft.json
Try to understand my solution in your previous question
How to deserialize json data in windows phone?
Your first JSON in that question was good and simple to use.
JSON, where field names are unique not convinient to deserialize. So, you got problems such as public class Hjeke and public class Second for each instance, when you use code generator.
Use JSON-structure with list of students:
"code": 0,
"message": "success",
"students": [
{
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
{
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}]
is good and flexible structure. Using this, you don't need to parse not obvious fields like
"details":{
"hjeke": {
and so on.
And work with them using classes, from my previous answer. The main idea - you need list of objects. public List<StudentDetails> students. Then, all students objects deserialized in List, which is easy to use.
As everybody mentioned your json seems to be very unflexible, huh.
You can extract the data you are interested in.
So this is your model:
public class StudentDetails
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
And this is how you can extract it:
var jsonObj = JObject.Parse(str);
// get JSON result objects into a list
var results = jsonObj["students"]["details"].Children().Values();
// serialize JSON results into .NET objects
var details = new List<StudentDetails>();
foreach (JToken result in results)
{
var st = result.ToString();
var searchResult = JsonConvert.DeserializeObject<StudentDetails>(st);
details.Add(searchResult);
}
I'm using a newtonsoft.json library here.
Your Response string has some mistakes man, its not a valid json
just small modification to be done as below:
{
"code": 0,
"message": "success",
"students": {
"details": {
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good"
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad"
}
}
}
}
you can make out the difference
Now Follow these steps:
1.Go to this link Json to C#
2.place your Json string there and generate C# class object
3.Now create this class in your solution
4.Now deserialize As below
var DeserialisedObject = JsonConvert.DeserializeObject<Your Class>(YourJsonString);
First, create the classes:
public class Hjeke
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Second
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Details
{
public List<Hjeke> hjeke { get; set; }
public List<Second> Second { get; set; }
}
public class Students
{
public List<Details> details { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public List<Students> students { get; set; }
}
After that, use JSON.NET to deserialize:
var deserialized = JsonConvert.DeserializeObject<Class1>(YourStringHere);
Do you have any influence over the json response? Details should probably be a JSONArray in this case, not an object with a varying amount of properties, since I assume that's what you mean is the issue here.
json ="{
"data": [
{
"id": "1000",
"from": {
"name": "Anthony Waema",
"category": "message",
"id": "192"
},
"message": "this is the message",
"updated_time": "2001-05-06T19:34:15+0000",
"likes": {
"data": [
{
"id": "100001692250255",
"name": "\u00dcnal Turanl\u0131"
},
{
"id": "100001060078996",
"name": "S\u00e9f\u00e2 K\u00e2ql\u00e4Nn"
}]
},
{
"id": "10150186255753553",
"from": {
"name": "another name",
"category": "message",
"id": "100001"
},
"message": "this is the message",
"updated_time": "2001-04-06T19:34:15+0000",
"likes": {
"data": [
{
"id": "1002345",
"name": "\u00dcnal Turanl\u0131"
},
{
"id": "100234",
"name": "S\u00e9f\u00e2 K\u00e2ql\u00e4Nn"
}]
}
}
]
}";
public class Allstatus
{
public List<sdata> data { get; set; }
public scpaging paging { get; set; }
}
public class sdata
{
public string id { get; set; }
public sfrom from { get; set; }
public string message { get; set; }
public string updated_time {get; set;}
public List<likesdata> likes { get; set; }
}
public class likesdata
{
public string id{ get; set; }
public string name{ get; set; }
}
public class sfrom
{
public string name {get; set;}
public string category {get; set;}
public string id {get; set;}
}
JavaScriptSerializer ser = new JavaScriptSerializer();
page = ser.Deserialize<allstatus>(json);
foreach (sdata cd in page.data)
{
foreach(likesdata ld in cd.likes.data)
{
Console.WriteLine(ld.id+"\t"+ld.name);
}
}
problem:
I need to parse the json and retrieve likes data.
I can access "from" data but not "likes" data.. I get nullreference error when I do this. help needed here.. Thanks.
Edit2:
Referring https://gist.github.com/973510, its clear from the returned json, that if a particular facebook message doesnt have any likes, then the returned json doesnt contain a property called likes. Hence likes property of sdata object is null. Thats just how the server returns the data.
There are two ways you can deal with this. Either do a manual check whether likes is null. Or initialize the likes property in the sdata constructor. And initialize the likesdata list in the likesdatacollection constructor.
Code:
public class sdata
{
// other properties
public likedatacollection likes { get; set; }
public sdata()
{
likes = new likedatacollection();
}
}
public class likedatacollection
{
public List<likesdata> data { get; set; }
public likedatacollection()
{
data = new List<likesdata>();
}
}
This way, even if fb doesnt return any likes, the constructors will initialize the properties, so they will not be null. You can then check whether likes.data.Count > 0. If yes, then fb returned likes, else fb didnt return likes.
Edit1:
From the OP's comment, its clear that the json is properly formed. Meaning, the json is as retrieved from some server api. Therefore it is the sdata class that is the culprit. Please look at this gist for the full solution.
The short version. For the simplest case, your c# classes need to follow the exact same structure as your json. As per the json, data has a property called likes. the likes object has a property called data which is an array of objects with properties id and name.
So your c# class sdata should have a property called likes of type likesdatacollection. This class should have a property data of type List<likesdata>...
Off topic, people generally seem to prefer Json.Net ... so you may want to use that. The reason I use it is because I need it to work in a .Net 2.0 code base ...
You should try running your JSON through a validator like JSON Lint. That should help you find any JSON errors.