parsing Json using system.web.script.seriarilization or using json.net - c#

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.

Related

Deserialize array from JSON in C#

So I am trying to deserialize an array from JSON into a C# class using Newtonsoft. I have seen tutorials and other questions on this, but I am running into problems as the array I want to get is not at the top level of the JSON. The JSON is structured like this, where I want to extract the "data" array and deserialize it:
"success": true,
"data": [
{
"key": "americanfootball_nfl",
"active": true,
"group": "American Football",
"details": "US Football",
"title": "NFL",
"has_outrights": false
},
{
"key": "aussierules_afl",
"active": true,
"group": "Aussie Rules",
"details": "Aussie Football",
"title": "AFL",
"has_outrights": false
},
{
"key": "basketball_euroleague",
"active": true,
"group": "Basketball",
"details": "Basketball Euroleague",
"title": "Basketball Euroleague",
"has_outrights": false
}
]}
I know that I first need to extract the data object from the JSON, and then parse that, but I am not too sure how. I have this class to deserialize the JSON:
public class SportsModel
{
public bool Success { get; set; }
public string Data { get; set; }
}
public class SportsData
{
public string Key { get; set; }
public bool Active { get; set; }
public string Group { get; set; }
public string Details { get; set; }
public string Title { get; set; }
public bool HasOutrights { get; set; }
}
And currently get the top level of the data using this:
SportsModel data = JsonConvert.DeserializeObject<SportsModel>(response);
I want to put the JSON array data into a list object, so that I can access it all
You only need to fix this part to make the serializer understand you're deserializing the Data field into a type of SportsData and not a string.
public class SportsModel
{
public bool Success { get; set; }
public List<SportsData> Data { get; set; }
}
Update
To get data into a list, I would assume you are referring to something of this nature
SportsModel result = JsonConvert.DeserializeObject<SportsModel>(response);
var sportsDataList = result.Data;
Your SportModels class needs to be updated to:
public class SportsModel
{
public bool Success { get; set; }
public List<SportsData> Data { get; set; }
}
SportsModel result = JsonConvert.DeserializeObject<SportsModel>(response);
And you will Data in a List.
What you can do is; go to visual studio and in edit menu menu and paste special
and click then paste json as class.
But first you need to copy the json string first.

Extracting a value from an array of objects [duplicate]

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 ;

c# get values from json

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 ;

C# WebApi Json Posting

I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
public object Post([FromBody] Account account)
{
Message msg = new Message();
msg.status = "Status";
return Request.CreateResponse(msg);
}
JSON
{
"Accounts": {
"id": "13456454",
"number": "222",
}
}
Your json:
{
"Accounts": {
"id": "13456454",
"number": "222",
}
}
It can be parsed to object with property Accounts which has id and number properties
If you want to post only one Account your json should be:
{
"id": "13456454",
"number": "222"
}
You only need to post id and number in following format:
{
"id": "13456454",
"number": "222",
}
This will wok for you.
Your Account object is null, because the C# code is inconsistent with JSON you provided. That's how MVC defends itself from badly formed requests.
Model suggests, that what you get in JSON are just these 2 pure fields, id and number, so JSON for it should look like this:
{
"id": "13456454",
"number": "222"
}
To make C# model adapted for provided JSON it should be built like this:
public class Accounts
{
public Account Accounts { get; set; }
}
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
And API Action prototype should look like this:
public object Post([FromBody] Accounts account)
By this you contain Account into another class with property Accounts resembling what you have in provided JSON.
However your naming scheme suggest that single request might contain more than single account. To achieve this C# Classes should look like this:
public class Accounts
{
public Account[] Accounts { get; set; }
}
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
And your JSON should contain object array:
{
"Accounts": [
{
"id": "13456454",
"number": "222",
},
{
"id": "23456",
"number": "125",
},
]
}
Of course that array can contain only single element, if you need so, but it will allow you to put more than one Account at once, as your naming suggests.
For future reference, you should be more precise at what you want to be the result, to make sure we know best how we should help you.
You are sending list of accounts from the client side but api is expecting a single object if you want to sent single object you can send single object from json file else you can change server object as List

How to deserialize json string in windows phone?

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.

Categories