How to deserialize json string in windows phone? - c#

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.

Related

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 ;

Not getting result when deserializing json using DataContractJsonSerializer

I have following json:
{
"Australia": {
"count": 2,
"records": {
"File1.ppt": {
"id": "123456789"
},
"File2.doc": {
"id": "987654321"
}
}
},
"PDFs.zip": {
"count": 0,
"records": {}
},
"Peru": {
"count": 2,
"records": {
"File3.PPT": {
"id": "897456123"
},
"File4.PPT": {
"id": "123546789"
}
}
},
"total count": 4
}
and to deserialize the above json I have defined some classes so that I can use these classes while deserializing my json into objects and below are the classes:
namespace GEO_Batch_Creation
{
[DataContract]
class BhpIdJson
{
[DataMember(Name = "objects")]
public Dictionary<string, Country[]> Countries { get; set; }
[DataMember(Name = "total count")]
public int TotalCount { get; set; }
}
[DataContract]
class Country
{
[DataMember(Name = "count")]
public int Count { get; set; }
[DataMember(Name = "records")]
public Dictionary<string, Record> Records { get; set; }
}
[DataContract]
class Record
{
[DataMember(Name = "filename")]
public string FileName { get; set; }
[DataMember(Name = "id")]
public Dictionary<string, string> BhpId { get; set; }
}
}
But when I use following code to deserialize the json I am getting only total count.
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BhpIdJson));
BhpIdJson bsObj2 = (BhpIdJson)deserializer.ReadObject(ms);
}
Please suggest me where I am doing mistake.
I don't think that this JSON is in correct format. I don't know if you got this from somewhere or made for yourself, but if the last one I recommend you to change the structure.
Even in C# you cant realy create a class that has the objects and the count of the object in the same List or Array etc.
Based on your class your JSON yhould look like this:
{
"objects": [
{
"name": "Australia",
"count": 2,
"records": [
{
"fileName": "File1.ppt",
"id": "123456789"
},
{
"fileName": "File2.doc",
"id": "987654321"
}
]
}
],
"total count": 4
}
As you can see you have to add Name or something to your Country class. I hope it helped.
Edit:
You can create a list like I mentioned above but it's not a good practice I think.

Deserializing JSON with Child and Inner Childs

I am familiar with JSON.net a bit and can Deserialize the JSON with basic structure (upto one child). I am currently in process of Deserializing the JSON that is returned from Netatmo API. The structure of JSON is complicated for me. Following is the basic structure of the JSON,
_id
place
location
Dynamic Value 1
Dynamic Value2
altitude
timezone
mark
measures
Dynamic Value 1
res
Dynamic Value 1
Dynamic Value 1
Dynamic Value 2
type
Dynamic Value 1
Dynamic Value 2
modules
Dynamic Value 1
Dynamic Value 1 and Dynamic Value 2 represents the values that is changed for each id. The complete JSON is given below,
{
"body": [{
"_id": "70:ee:50:02:b4:8c",
"place": {
"location": [-35.174779762001, -5.8918476117544],
"altitude": 52,
"timezone": "America\/Fortaleza"
},
"mark": 0,
"measures": {
"02:00:00:02:ba:2c": {
"res": {
"1464014579": [16.7, 77]
},
"type": ["temperature", "humidity"]
},
"70:ee:50:02:b4:8c": {
"res": {
"1464014622": [1018.1]
},
"type": ["pressure"]
}
},
"modules": ["02:00:00:02:ba:2c"]
}, {
"_id": "70:ee:50:12:40:cc",
"place": {
"location": [-16.074257294385, 11.135715243973],
"altitude": 14,
"timezone": "Africa\/Bissau"
},
"mark": 14,
"measures": {
"02:00:00:06:7b:c8": {
"res": {
"1464015073": [26.6, 78]
},
"type": ["temperature", "humidity"]
},
"70:ee:50:12:40:cc": {
"res": {
"1464015117": [997]
},
"type": ["pressure"]
}
},
"modules": ["02:00:00:06:7b:c8"]
}],
"status": "ok",
"time_exec": 0.010364055633545,
"time_server": 1464015560
}
I am confused by looking at the complex structure of this JSON. For single level of JSON I have used this code in the past,
IList<lstJsonAttributes> lstSearchResults = new List<lstJsonAttributes>();
foreach (JToken objResult in objResults) {
lstJsonAttributes objSearchResult = JsonConvert.DeserializeObject<lstJsonAttributes>(objResult.ToString());
lstSearchResults.Add(objSearchResult);
}
But for so many child I have yet to understand how the object class will be created. Any guidance will highly appreciated.
Update:
This is what I have achieved so far.
I have created a main class as below,
public class PublicDataClass
{
public string _id { get; set; }
public PublicData_Place place { get; set; }
public string mark { get; set; }
public List<string> modules { get; set; }
}
and "Place" class is as follow,
public class PublicData_Place
{
public List<string> location { get; set; }
public string altitude { get; set; }
public string timezone { get; set; }
}
Then I have Deserialized the object in the following code line,
var obj = JsonConvert.DeserializeObject<List<PublicDataClass>>(jsonString);
I can now successfully get all the data except the "measures" which is little bit more complicated.
Using json.net, JSON objects that have arbitrary property names but fixed schemas for their values can be deserialized as a Dictionary<string, T> for an appropriate type T. See Deserialize a Dictionary for details. Thus your "measures" and "res" objects can be modeled as dictionaries.
You also need a root object to encapsulate your List<PublicDataClass>, since your root JSON container is an object like so: { "body": [{ ... }] }.
Thus you can define your classes as follows:
public class RootObject
{
public List<PublicDataClass> body { get; set; }
public string status { get; set; }
public double time_exec { get; set; }
public int time_server { get; set; }
}
public class PublicDataClass
{
public string _id { get; set; }
public PublicData_Place place { get; set; }
public int mark { get; set; }
public List<string> modules { get; set; }
public Dictionary<string, Measure> measures { get; set; }
}
public class PublicData_Place
{
public List<double> location { get; set; } // Changed from string to double
public double altitude { get; set; } // Changed from string to double
public string timezone { get; set; }
}
public class Measure
{
public Measure()
{
this.Results = new Dictionary<string, List<double>>();
this.Types = new List<string>();
}
[JsonProperty("res")]
public Dictionary<string, List<double>> Results { get; set; }
[JsonProperty("type")]
public List<string> Types { get; set; }
}
Then do
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
var obj = root.body;
I've worked with XML for a few years and my change to JSON structure I've got a little confused too, always that I want to see how an object look like I use this web site jsoneditoronline Just copy and paste your JSON and click on arrow to parse to an object, I hope it helps until you get used to JSON structure.

Is this json format correct?

I have a json data when i'm trying to parse it returns error incorrect syntax please help me found the syntax error.
[{"isData":"Yes","Details":"[{"Id":"70","Name":"Test","FileName":"Uploaded","FileFormat":".mp4","FileType":"Video","FileDuration":"00:30:00 ","StartTime":"/Date(1372617000000)/","EndTime":"/Date(1372681771000)/","File":"2562013172331815635077778118152815.mp4"}]"}]
And this is the class that is used to serialize data, i am using javascript serializer
public enum Data
{
Yes,
No
}
public class MessageResponse()
{
public string isData { get; set; }
public string Details { get; set; }
}
List<MessageResponse> response = new List<MessageResponse>();
string strJson="[{"Id":"70","Name":"Test","FileName":"Uploaded","FileFormat":".mp4","FileType":"Video","FileDuration":"00:30:00 ","StartTime":"/Date(1372617000000)/","EndTime":"/Date(1372681771000)/","File":"2562013172331815635077778118152815.mp4"}]";
var newData = new MessageResponse
{
isData = Data.Yes.ToString(),
Details = strJson
};
response.Add(newData);
var jsonSerialiser1 = new JavaScriptSerializer();
string result = jsonSerialiser1.Serialize(response);
That's invalid JSON. The Details property is incorrectly formatted. You should remove the quotes around the value. It should be like this:
[
{
"isData": "Yes",
"Details": [
{
"Id": "70",
"Name": "Test",
"FileName": "Uploaded",
"FileFormat": ".mp4",
"FileType": "Video",
"FileDuration": "00:30:00 ",
"StartTime": "/Date(1372617000000)/",
"EndTime": "/Date(1372681771000)/",
"File": "2562013172331815635077778118152815.mp4"
}
]
}
]
or if you want Details to be a string property (representing JSON), which is kinda lame, you should properly escape the double quotes:
[
{
"isData": "Yes",
"Details": "[{\"Id\":\"70\",\"Name\":\"Test\",\"FileName\":\"Uploaded\",\"FileFormat\":\".mp4\",\"FileType\":\"Video\",\"FileDuration\":\"00: 30: 00\",\"StartTime\":\"/Date(1372617000000)/\",\"EndTime\":\"/Date(1372681771000)/\",\"File\":\"2562013172331815635077778118152815.mp4\"}]"
}
]
This structure you will be able to map to your current object model. But I would recommend you using the first approach.
Remove the " from the details data:
[{
"isData":"Yes",
"Details":
[{
"Id":"70",
"Name":"Test",
"FileName":"Uploaded",
"FileFormat":".mp4",
"FileType":"Video",
"FileDuration":"00:30:00",
"StartTime":"/Date(1372617000000)/",
"EndTime":"/Date(1372681771000)/",
"File":"2562013172331815635077778118152815.mp4"
}]
}]
Details should be of type class (i.e. user defined class) and it should hold all the properties.
public class Details
{ public int Id {get; set;} ... }
Firstly your json is invalid.
It should not have the " before and after the [ ]
[
{
"isData": "Yes",
"Details": [
{
"Id": "70",
"Name": "Test",
"FileName": "Uploaded",
"FileFormat": ".mp4",
"FileType": "Video",
"FileDuration": "00: 30: 00",
"StartTime": "/Date(1372617000000)/",
"EndTime": "/Date(1372681771000)/",
"File": "2562013172331815635077778118152815.mp4"
}
]
}
]
Secondly, your class could be improved to be:
public class MessageResponse
{
public string isData { get; set; }
public Details Details { get; set; }
}
public class Details
{
public int Id { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public string FileFormat { get; set; }
public string FileType { get; set; }
public string FileDuration { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string File { get; set; }
}
You would probably want to set up the correct data types though for things like Start Time etc...

Parsing multi-level JSON array

I'm trying to get objects from a multi-level JSON array. This is the an example table:
array(2) {
["asd"]=>
array(3) {
["id"]=>
int(777)
["profile"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random#example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
["name"]=>
string(5) "Grega"
}
["be"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random#example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
}
The string I'm trying to reach is either of the emails (example). This is how I try it:
public class getAsd
{
public string asd;
}
public class Profile
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public string age { get; set; }
}
}
And then using JavaScriptSerilization.Deserilize<Asd>(jsonData); to deserilize it, but when I try the same with "Profile", it gives me the following error:
No parameterless constructor defined for type of 'System.String'.
JSON:
{"asd":{"id":777,"profile":{"username":"grega","email":"random#example.com","image":"http...image.jpg","age":26},"name":"Grega"},"be":{"username":"grega","email":"random#example.com","image":"http...image.jpg","age":26}}
And idea what might be wrong?
[EDIT: Smarm removed. OP did add JSON in an edit.]
Your profile class, as JSON, should resemble the following.
{
"username":"grega",
"email":"random#example.com",
"image":"http...image.jpg",
"age":"26",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
}
array should not show up in JSON unless its part of a property name ("codearray") or property value("There's no 'array' in JSON. There's no 'array' in JSON.").
Arrays of objects in JSON are encased in square brackets [] and comma-delimited. An array/collection of profiles in JSON:
[
{
"username":"gretta",
"email":"mrshansel#example.com",
"image":"http...image.jpg",
"age":"37",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
},
{
"username":"methusaleh",
"email":"old#men.org",
"image":"http...image.jpg",
"age":"2600",
"roles": [
{"name": "foo"},
{"name": "},
{"name": "bar"}
]
},
{
"username":"goldilocks",
"email":"porridge#bearshous.com",
"image":"http...image.jpg",
"age":"11",
"roles": [
{"name": "foo"}
]
}
]
While that may not fully answer your question, could you start with that and update your question?
EDIT:
See this answer by Hexxagonal for the complete approach.
Alright, here was what a "basic" version of your classes would be. You should really follow a standard of having properties have their first letter capitalized. Since you did not do this earlier, I maintained that style.
public class Type1
{
public TypeAsd asd { get; set; }
public TypeBe be { get; set; }
}
public class TypeAsd
{
public int id { get; set; }
public TypeBe profile { get; set; }
public string name { get; set; }
}
public class TypeBe
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public int age { get; set; }
}
You deserialization code would then look something like the following:
string jsonString = "{\"asd\":{\"id\":777,\"profile\":{\"username\":\"grega\",\"email\":\"random#example.com\",\"image\":\"http...image.jpg\",\"age\":26},\"name\":\"Grega\"},\"be\":{\"username\":\"grega\",\"email\":\"random#example.com\",\"image\":\"http...image.jpg\",\"age\":26}}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Type1 obj = serializer.Deserialize<Type1>(jsonString);

Categories