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.
Related
I am starting to use Azure IoT hub and I configured my endpoints and servicehub to learn from it with a route.
In this route I specify that when a message says level = critical that it forwards the message to my endpoint like explained in the following link: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-process-d2c
The difference is that I use my own code for my temperature sensor with a programmed DTO and that I send it as one big json message (see code)
DTO class:
[DataContract]
class Bmp280DTO
{
[DataMember]
public Guid guid { get; set; }
[DataMember]
public string deviceName { get; set; }
[DataMember]
public float tempSensorValue { get; set; }
[DataMember]
public float pressureSensorValue { get; set; }
[DataMember]
public float altitudeSensorValue { get; set; }
[DataMember]
public DateTime measurementTime { get; set; }
[DataMember]
public string measurename { get; set; }
[DataMember]
public string level { get; set; }
public Bmp280DTO() { }
public Bmp280DTO(Guid id, String Device, float TmpSensorValue, float PrSensorValue, float AlSensorValue)
{
this.guid = id;
this.deviceName = Device;
this.tempSensorValue = TmpSensorValue;
this.pressureSensorValue = PrSensorValue;
this.altitudeSensorValue = AlSensorValue;
this.measurementTime = DateTime.Now;
this.measurename = "LightSensor";
this.level = DetermineMessageLevel(TmpSensorValue);
}
public string ToJson()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Bmp280DTO));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, this);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
return json;
}
public string DetermineMessageLevel(float temperaturesensorvalue)
{
if(temperaturesensorvalue > 22)
{
return "critical";
}
return "normal";
}
}
Message send:
private void SendBmp280Data(Bmp280DTO AzureBmp280Data)
{
System.Text.StringBuilder Bmp280JsonMessage = new System.Text.StringBuilder();
Bmp280JsonMessage.Append(AzureBmp280Data.ToJson());
MessageCommands.SendMessage(Bmp280JsonMessage.ToString());
}
Examples of message:
{"guid":"xxxx","deviceName":"Bmp280Sensor","tempSensorValue":23.59763,"pressureSensorValue":98792.11,"altitudeSensorValue":213.046539,"measurementTime":"2017-02-23T05:34:00.4544388-08:00","measurename":"LightSensor","level":"critical"}
The message is received in the IOT hub but not forwarded to the endpoint.
What am I doing wrong? Are you not able to query json object messages? And if that's the case how do you do it then? I don't want to send unnecessary messages.
It seems that this was a problem with the encoding while sending the message.
I encoded the message in UTF8 while it needed to be done in ASCII value's.
I also could add message-properties to make it more obvious.
So as following:
var messageString = JsonConvert.SerializeObject(AzureBmp280Data);
Debug.WriteLine("Message Sent: {0}", messageString, null);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
message.Properties.Add("level", "critical");
I need to bind the json webservice into my list view adapter. I am getting error. Need to bind those values in the List View
[Activity(Label = "ListView", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private ListView mListView;
public virtual IListAdapter ListAdapter { get; set; }
private List<RootObject> mUsers;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mListView = FindViewById<ListView>(Resource.Id.listView1);
var url = "https://www.yellowbox.com.sg/index.php?route=api/app/getusers";
// Syncronious Consumption
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
var TEST = JsonConvert.DeserializeObject <RootObject>(content);
// getting null values in "TEST"
//mUsers =????
ListAdapter = new ArrayAdapter<RootObject>(this, Android.Resource.Layout.SimpleListItem1, mUsers);
mListView.Adapter = ListAdapter;
}
My class:
public class RootObject
{
public string id { get; set; }
public string username { get; set; }
public string total_deliveries { get; set; }
}
how can i parse this json response and create c# object
{"Response":"valid","Files":{"0":{"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":1},"1":{"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":2}}}
i have c# class
public class Files
{
public string fileURL;
public string fileVersion;
}
WebClient wc=new WebClient();
string code=wc.DownloadString("http://somedomain.com/GetLatestFiles.php");
List<Files> f=ParseJson(code);
how can i parse this json please help. I need to implement ParseJson which will return files list or can i deserialize this response to c# class?
Thankyou
Edit implemented some solution but its very slow?
public class LatestFile
{
public string fileURL;
public string fileVersion;
}
private List<LatestFile> ParseJson(string code)
{
List<LatestFile> files = new List<LatestFile>();
dynamic jObj = JsonConvert.DeserializeObject(code);
foreach (var child in jObj.Files.Children())
{
string index = child.Name;
string url = child.First.FileURL.Value;
string version = child.First.FileVersion.Value.ToString();
LatestFile f = new LatestFile();
f.fileURL = url;
f.fileVersion = version;
files.Add(f);
}
return files;
}
Based on #Brian Rogers answer below i am able to implement the generic solution working fast and efficiently.Thanks
https://dotnetfiddle.net/tC0Dws
Try defining your classes like this:
public class RootObject
{
public string Response { get; set; }
public Dictionary<string, LatestFile> Files { get; set; }
}
public class LatestFile
{
public string FileURL { get; set; }
public string FileVersion { get; set; }
}
And make your helper method like this:
private List<LatestFile> ParseJson(string json)
{
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
return obj.Files.Values.ToList();
}
Fiddle: https://dotnetfiddle.net/vpre5H
According to the JSON you provided you have three different objects there. First with Response and Files fields. Second - it looks like it's intended to be a collection but with current implementation it's an object - with fields 0 and 1. And third one with fields FileURL and FileVersion.
You can use DataContractJsonSerializer which is available starting from .Net 4.5. It's in System.Runtime.Serialization.Json namespace.
To parse your JSON you need following data structure:
[DataContract]
public class JsonResponse
{
[DataMember(Name = "Response")]
public string Response { get; set; }
[DataMember(Name = "Files")]
public Files Files { get; set; }
}
[DataContract]
public class Files
{
[DataMember(Name = "0")]
public MyFile Frst { get; set; }
[DataMember(Name = "1")]
public MyFile Scnd { get; set; }
}
[DataContract]
public class MyFile
{
[DataMember(Name = "FileURL")]
public string FileURL { get; set; }
[DataMember(Name = "FileVersion")]
public int FileVersion { get; set; }
}
To make testing easier I'm using your sample as a string but you can easily use URL or a Stream:
static string json = #"
{
""Response"":""valid"",
""Files"":
{
""0"":
{
""FileURL"":""htp:\/\/somedomain.com\/1.exe"",""FileVersion"":""1""
},
""1"":
{
""FileURL"":""htp:\/\/somedomain.com\/1.exe"",""FileVersion"":""2""
}
}
}";
static void Main(string[] args)
{
var serializer = new DataContractJsonSerializer(typeof(JsonResponse));
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(JsonResponse));
using (MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(json)))
{
JsonResponse response = (JsonResponse)js.ReadObject(ms);
}
}
And that's the result:
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
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.