JSON parsing in windows phone 8 - json

i am new to windows phone development and so by references implemented some code but i am not able to get the desired result.
i want to parse a JSON that is received as a response from the server.
Please find below my code.
class JSONParsing
{
public Status response { get; set; }
public static void webClient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Result))
{
try
{
JSONParsing root = JsonConvert.DeserializeObject<JSONParsing>(e.Result);
// root is null here
JObject obj = root.response.statusDetail;
// from here it goes to Catch block
foreach (KeyValuePair<string, JToken> pair in obj)
{
string key = pair.Key;
foreach (JObject detail in pair.Value as JArray)
{
string Code = detail["Code"].ToString();
string Msg = detail["Msg"].ToString();
string RegistrationID = detail["RegistrationID"].ToString();
string Name = detail["Name"].ToString();
string Phone = detail["Phone"].ToString();
string email = detail["email"].ToString();
string password = detail["password"].ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Cause of Exception is " + ex.Message);
// exception is-- "Object reference not set to an instance of an object."
}
} // if for empty
}
}
public class Status
{
public string Code { get; set; }
public string Msg { get; set; }
public object RegistrationID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string email { get; set; }
public string password { get; set; }
[JsonProperty("")]
public JObject statusDetail { get; set; }
}
public class RootObject
{
public List<Status> Status { get; set; }
public int success { get; set; }
}
}
Please Help.

If root is null the class 'JSONParsing' is not having same class structure as the json
and since root is null, accessing property inside a null('root.response.statusDetail') will throw an exception
you can use http://json2csharp.com/ to get the class structure of the json

Related

How to deserialize specific Json

Hi guys i try to deserialize a json but this result null , posible its so simple but i cant resolve now , i try this forms, and i use Newtonsoft
if (response.Content.Contains("error"))
{
JObject jObject = JObject.Parse(response.Content);
dynamic x = JsonConvert.DeserializeObject<Error>(response.Content);
error = JsonConvert.DeserializeObject<Error>(response.Content);
JArray recibos = (JArray)jObject["error"];
return error;
}
this its the json my response.content
"{\"error\":{\"code\":-10,\"message\":{\"lang\":\"en-us\",\"value\":\"The warehouse is not defined for the item. [OWOR.Warehouse]\"}}}"
and my class
public class Error
{
public int code { get; set; }
public Message message { get; set; }
public class Message
{
public string lang { get; set; }
public string value { get; set; }
}
}
try this
if (response.Content != null)
{ {
Data data = JsonConvert.DeserializeObject<Data>(response.Content);
}
and add class Data (you can change name)
public class Data
{
public Error error {get; set;}
}
Your Model class is incorrect to which you are trying to de-serialize your JSON string. Change your Model classes to:
public class Message
{
public string lang { get; set; }
public string value { get; set; }
}
public class Error
{
public int code { get; set; }
public Message message { get; set; }
}
public class Root
{
public Error error { get; set; }
}
And your de-serialization will be:
if(string.IsNotNullOrEmpty(response.Content)
{
if (response.Content.Contains("error"))
{
var error = JsonConvert.DeserializeObject<Root>(response.Content);
return error;
}
}
Your error variable will contain the contents of the deserialized result and you can access the required data.
Example working with your JSON string: https://dotnetfiddle.net/NZuwtl

WP read user_id from JSON and show it

I want to show user_id from the following JSON:
[{"username":"Kac26","email":"xklemenx#gmail.com","city":"Slovenj Gradec","id":"15"}]
So I save this JSON to class. I get JSON from my webpage.
My class:
public class Class2
{
public string username{ get; set; }
public string email { get; set; }
public string city { get; set; }
public int id { get; set; }
}
Saving JSON to class:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response= await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
}
Then I want to show user id in textbox_id when i press button.
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
textbox_id.Text = Class2.id;
}
But error shows up when I try to reach Class2.id
Anyone know how to do that? And do I save json to class correct?
Thanks!!!
In "Saving JSON to class", I don't see where you are actually doing that. Here's how you would deserialize the string returned by the service:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response = await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
Class2 myClass2 = null;
try
{
var jsonSerializer = new DataContractJsonSerializer(typeof(Class2));
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response)))
{
myClass2 = jsonSerializer.ReadObject(stream) as Class2;
}
}
catch
{
// serialization error occurred
}
// do something with myClass2
}
Also, FYI if you don't want the property names on your response class to match the JSON properties (for example, not be lower case), you can use DataContractAttribute and DataMemberAttribute on your class like so:
[DataContract]
public class Class2
{
[DataMember(name = "username")]
public string UserName { get; set; }
[DataMember(name = "email")]
public string EMail { get; set; }
[DataMember(name = "city")]
public string SomeCompletelyDifferentNameForCity { get; set; }
[DataMember(name = "id")]
public int Id { get; set; }
}
Class2.id is a static access to a non-static property of Class2. You have to create an instance of Class2 with new Class2(); at some point and then you can access the property.

Read Object from JSON web page in Windows Phone 8.1

I want to read some List<> of Object from a JSON file, which is generated by a PHP file.
When I try to compile it, I have some problems, it seems that the Smartphone is waiting something. Also I'm not sure if the read is correct for Windows Phone. Thank you in advance for your help !
This is the JSON file example:
{"giocatori":[{"Giocatore":"124","Cognome":"DE SANCTIS","Ruolo":"P","Squadra":"ROM"},{"Giocatore":"140","Cognome":"MIRANTE","Ruolo":"P","Squadra":"PAR"},{"Giocatore":"156","Cognome":"SKORUPSKI","Ruolo":"P","Squadra":"ROM"}],"success":1}
These are the Objects:
public class Giocatori
{
public string Giocatore { get; set; }
public string Cognome { get; set; }
public string Ruolo { get; set; }
public string Squadra { get; set; }
public override string ToString()
{
return Giocatore + " " + Cognome + " " + Ruolo + " " + Squadra;
}
}
public class RootObject
{
public List<Giocatori> giocatori { get; set; }
public int success { get; set; }
}
And here are the methods:
private async Task<RootObject> getPlayers()
{
Uri serviceUri = new Uri("myURL");
HttpClient client = new HttpClient();
string jsonString = await client.GetStringAsync(serviceUri);
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
RootObject RootObject = new RootObject();
DataContractJsonSerializer ser = new DataContractJsonSerializer(RootObject.GetType());
RootObject = ser.ReadObject(ms) as RootObject;
return RootObject;
}
private void loadPlayers()
{
RootObject players = getPlayers().Result;
setComboboxs(players.giocatori); // The method which I need to use the
}
Download JSON.Net package via Nuget.
Right Click project > Manage Nuget > Json.net > Install
According to http://json2csharp.com/ your class should look like this.
public class Giocatori
{
public string Giocatore { get; set; }
public string Cognome { get; set; }
public string Ruolo { get; set; }
public string Squadra { get; set; }
}
public class RootObject
{
public List<Giocatori> giocatori { get; set; }
public int success { get; set; }
}
RootObject can be renamed to whatever you like.
When you receive your JSON do
JsonConvert.DeserializeObject<RootObject>("jsonstring");

Parsing complex JSON

I want to parse a complex JSON on WP7. First I have to parse a JSON feed and I retrieve data to parse second JSON feed.
To parse the first feed I use this web service
http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=...
after that we use the code and the station's name to parse the second feed
http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=....&id=...
This my code but it doesn't work:
public static class Parser
{
public static string resultats;
public static reponse[] obj = new reponse[]{new reponse(),new reponse()};
public static reponse1 obj1 = new reponse1();
public static void HttpsCompleted_reponse(object sender, DownloadStringCompletedEventArgs e)
{
Horaire hre =new Horaire();
try
{
var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultats));
var ser = new DataContractJsonSerializer(typeof(reponse1));
obj1 = (reponse1)ser.ReadObject(ms);
}
catch
{
WebClient wc = new WebClient();
//wc.DownloadStringCompleted += HttpsCompleted_reponse1;
wc.DownloadStringAsync(new Uri("http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=" +hre.gettxt()));
Debug.WriteLine("youuuuuuuuuuuuuuuuuuuuuuuppppppppppiiii");
}
}
/*
public static void HttpsCompleted_reponse1(object sender, DownloadStringCompletedEventArgs e)
{
try
{
var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultats));
var ser = new DataContractJsonSerializer(typeof(Gare));
obj1 = (reponse1)ser.ReadObject(ms);
}
catch
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted_reponse;
wc.DownloadStringAsync(new Uri("http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=" + obj.success.Gares.Eleme + "&id=" + obj.success.id));
}
}
*/
}
public class Depart
{
[DataMember(Name = "type")]
public string type { get; set; }
[DataMember(Name = "heure")]
public string heure { get; set; }
[DataMember(Name = "destination")]
public string destination { get; set; }
[DataMember(Name="attention")]
public string attention { get; set; }
[DataMember(Name = "retards")]
public string [] retards { get; set; }
[DataMember(Name = "source")]
public string source { get; set; }
public Depart()
{
}
}
public class Success {
[DataMember(Name = "nom")]
public string nom { get; set; }
[DataMember(Name = "id")]
public int id { get; set; }
[DataMember(Name = "departs")]
public Depart[] departs { get; set; }
public Success()
{
this.departs = new Depart[0];
}
}
public class Success1
{
[DataMember(Name="Gares")]
public Gare[] Gares { get; set; }
public Success1()
{
this.Gares = new Gare[0];
}
}
public class Gare{
[DataMember(Name="Nom")]
public string Nom { get; set; }
[DataMember(Name="code")]
public int code { get; set; }
public Gare()
{
}
}
public class reponse
{
[DataMember(Name = "code")]
public string code{get;set;}
[DataMember(Name = "success")]
public Success1 success{get;set;}
public reponse()
{
this.success = new Success1();
}
}
public class reponse1 {
[DataMember(Name = "code")]
public string code { get; set; }
[DataMember(Name = "success")]
public Success success { get; set; }
public reponse1()
{
this.success = new Success();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//for (int i=0; i<=Parser.obj1.Length;i++)
Debug.WriteLine(Parser.obj1.success.nom);
}
}
There are several problems in your code. But even if you solved them you wouldn't be able to parse the list of received stations with DataContractJsonSerializer out of the box.
Explanation:
The web site offering the web service you are using says a response from your first "JSON feed" looks like this:
{"code":201,"success":{"gares":{"villefranche-d''alb.-ce":1750,"villefranche
de rgue-12":1749,...}}}
Have a look at the stations and their IDs:
{"villefranche-d''alb.-ce":1750,"villefranche de rgue-12":1749,...}
This is an associative array where the keys and values are not explicitly decorated with "Key" and "Value". But these decorations are necessary for DataContractJsonSerializer to parse the JSON. They would have to be in format
[{“Key”:“villefranche-d''alb.-ce”,“Value”:“1750”},{“Key”:“villefranche
de rgue-12”,“Value”:“1749”}]
to be properly parsed by DataContractJsonSerializer. (The reason is that this serializer supports more complex types than int and string to be used as keys and values.)
This blog post contains a very good description of the matter and how JavaScriptSerializer could be the solution. But unfortunately this class isn't available in Silverlight.
More people having similar problems like you:
Deserialization problem with DataContractJsonSerializer
.NET: Can I use DataContractJsonSerializer to serialize to a JSON associative array?
https://json.codeplex.com/discussions/258083
https://connect.microsoft.com/VisualStudio/feedback/details/558686/
Solution:
Use Json.NET.
Have a look at json.NET, it should provide you with linq2json and a simple serialise to object.

JavaScriptSerializer Question

I am having some issues DeSerializing the following Json, it runs, throws no errors however the props in the class are all null so it is obviously not working.
{ "realms":[ { "type":"pve", "queue":false, "status":true, "population":"medium", "name":"Malfurion", "slug":"malfurion" } ] }
The above JSON is the jsonResult string so string jsonResult = the above JSON
My code:
public class Realm
{
public string type { get; set; }
public bool queue { get; set; }
public bool status { get; set; }
public string population { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
var realm = javaScriptSerializer.Deserialize<Realm>(jsonResult);
There are no props in the object because the object contains a single array with a single object in the array.