I am trying to consume an API.
I want to store following Request in an Object: http://api.swissunihockey.ch/rest/v1.0/clubs/655
The Problem is, that the Object is initialized but all the values are null.
I can receive the data and generate an output as a string. But the De-serialization to the Object doesn't work. Can you help?
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://api.swissunihockey.ch/rest/v1.0/clubs/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await client.GetAsync("615");
var club = await response.Content.ReadAsAsync<Club>();
Console.WriteLine(club.Name);
Console.Read();
}
catch (HttpRequestException e)
{
if (e.Source != null)
{
Console.WriteLine("HttpRequestException source: {0}", e.Source);
}
}
}
}
This is the Club class I am trying to store the data:
class Club
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string Canton { get; set; }
public string Phone { get; set; }
public string Url { get; set; }
}
You need another class containing Club which will be deserialized further.
class Response
{
public Club Club { get; set; }
}
Then deserialize as
var res = await response.Content.ReadAsAsync<Response>();
var club = res.Club;
Once you have the string from the response, use the package that Web API already references from Nuget, Json.Net by Newtonsoft.Json1, and call Club c = JsonConvert.Deserialize<Club>(responseString);
I find this to be far simpler than the built in Data Contracts already mentioned.
Try to look on the microsoft related documentation:
http://msdn.microsoft.com/en-us/library/hh674188.aspx
You need to create a data contract and then process the request with this contract.
For example for your, the data contract may be something like:
[DataContract]
class Club
{
[DataMember(Name = "Id")]
public int Id { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Street")]
public string Street { get; set; }
[DataMember(Name = "Zip")]
public string Zip { get; set; }
[DataMember(Name = "City")]
public string City { get; set; }
[DataMember(Name = "Canton")]
public string Canton { get; set; }
[DataMember(Name = "Phone")]
public string Phone { get; set; }
[DataMember(Name = "Url")]
public string Url { get; set; }
}
Then look at chapter "process the request" of the documentation to handle your data.
Related
I'm trying to deserialise a JSON which conatains a series of "Clients" in succession from an API Call:
{"resource":[{"ClientID":1,"ClientName":"Name 1","ClientIntID":"TEST001","ClientCreatedDate":"2018-05-10 00:00:00"},{"ClientID":2,"ClientName":"Name 2","ClientIntID":"TEST002","ClientCreatedDate":"2018-05-10 03:10:47"},{"ClientID":3,"ClientName":"TestAPI","ClientIntID":"API001","ClientCreatedDate":"2018-05-10 03:30:14"},{"ClientID":4,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:03:40"},{"ClientID":5,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:28"},{"ClientID":6,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:31"},{"ClientID":7,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:32"},{"ClientID":8,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:35"}]}
into a List of Clients.
This is my code to deserialise:
IRestResponse<List<Client>> response = restClient.Execute<List<Client>>(request);
var content = response.Content;
var data = response.Data;
//Trying to check output of each Client in List:
foreach(Client c in data)
{
Console.WriteLine(c.ClientName);
}
This is my Client Class:
public class Client
{
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
I'm getting a list that is null, however when I change the code to simply cast into one Client only, it correctly stores the first client in the JSON response.
Any tips?
Your answer is in the form of the following format, so you have to deserialize into RootObject
public class Resource {
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
public class RootObject{
public List<Resource> resource { get; set; }
}
I am calling a PHP function from c# as below
using (var client = new WebClient())
{
string URL = "http://site.or/services/LoadMemberData.php";
NameValueCollection formData = new NameValueCollection();
formData["id"] = "123";
byte[] responseBytes = client .UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
}
once it completed the responsefromserver contain the some error message in case of error or details of the member in case of success
as below
{"result":{"success":true,"message":"","errorcode":0},"response":{"id":"123","full_name":"tom Vin","mobile_no":"02343434","phone_no":null,"country_code":"123312","country_of_residence":"","email":"ff#gmail.com","passport_no":"hedf"}}
how can i seperate the result into variables?
You can generate your models by json2csharp tool like this:
public class Result
{
public bool success { get; set; }
public string message { get; set; }
public int errorcode { get; set; }
}
public class Response
{
public string id { get; set; }
public string full_name { get; set; }
public string mobile_no { get; set; }
public object phone_no { get; set; }
public string country_code { get; set; }
public string country_of_residence { get; set; }
public string email { get; set; }
public string passport_no { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public Response response { get; set; }
}
Then deserialize your input with Newtonsoft.Json library:
var input =
"{\"result\":{\"success\":true,\"message\":\"\",\"errorcode\":0},\"response\":{\"id\":\"123\",\"full_name\":\"tom Vin\",\"mobile_no\":\"02343434\",\"phone_no\":null,\"country_code\":\"123312\",\"country_of_residence\":\"\",\"email\":\"ff#gmail.com\",\"passport_no\":\"hedf\"}}";
var result = JsonConvert.DeserializeObject<RootObject>(input);
EDIT: Based on #Sir Rufo comment: you can generate your models with jsonutils.com. This site allow you to generate data annotations like this:
[DataContract]
public class Response
{
[DataMember(Name="full_name")]
public string FullName { get; set; }
so you can have a convenient C# naming for your fields
I am trying to make a simple app with Xamarin and the Riot Games API. I have trouble accessing summoner information. It works only with my username due to the way that my deserialization is done I think.
This is my code:
public async void GetSummonerInformation()
{
using (var client = new HttpClient())
{
var result = await client.GetStringAsync(url);
var res = JsonConvert.DeserializeObject<RootObject>(result);
sumName = res.psychoal3x.name;
}
}
public class Psychoal3x
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
public class RootObject
{
public Psychoal3x psychoal3x { get; set; }
}
The problem is that if I change my username to something else then it won't work since it will search for psychoal3x in the RootObject class. Anyone know how to fix this?
EDIT
Ok so i changed the code a bit and this is how it looks like
This is the modified code
try
{
using (var httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<Dictionary<string, SummonerDto>>(result);
var name1 = data.First().Value.name;
var id = data.First().Value.id;
var profileIconId1 = data.First().Value.profileIconId;
var revisionDate1 = data.First().Value.revisionDate;
sumId = id;
sumProfileIconId = profileIconId1;
sumRevisionDate = revisionDate1;
System.Diagnostics.Debug.WriteLine("{0} this is the {1}", data.First().Value.name, data.First().Value.profileIconId);
}
}catch(Exception ex)
{ System.Diagnostics.Debug.WriteLine(ex.Message); }
public class SummonerDto
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
where sumName is the account name that is changed when the api is called.
You're close, but don't hardcode the username into your model classes. Assuming the API you are calling is this one, I'd recommend a structure like this:
public class SummonerDto
{
public int Id { get; set; }
public string Name { get; set; }
public int ProfileIconId { get; set; }
public int SummonerLevel { get; set; }
public long RevisionDate { get; set; }
}
According to the API docs, the return type is Dictionary<string, SummonerDto>. You can use JSON.NET to deserialize this easily:
var data = JsonConvert.DeserializeObject<Dictionary<string, SummonerDto>>(result);
That means that there will be a key-value pair with the key "psychoal3x" and a SummonerDto object as the value. You can get the first returned value by using First():
var summoner = data.First().Value;
From there, you can access all the properties, such as Name.
Here's a working fiddle based on the JSON data you posted in the comments: https://dotnetfiddle.net/xEUXa6
I am trying to parse a whois json response but when I try parse it I get null values.
string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
html = reader.ReadToEnd();
}
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);
Object
class Class1
{
public string created { get; set; }
}
can anyone please point what I am doing wrong here ?
Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.
You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.
class Class1
{
public Response Response { get; set; }
}
class Response
{
public string created { get; set; }
}
Then you can use this:
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);
UPDATE
Also, here's an example of how to use the dynamic:
var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;
There is nice app to convert json to .net class:
public class Registrar
{
public string id { get; set; }
public string name { get; set; }
public object email { get; set; }
public string url { get; set; }
}
public class Response
{
public string name { get; set; }
public string idnName { get; set; }
public List<string> status { get; set; }
public List<string> nameserver { get; set; }
public object ips { get; set; }
public string created { get; set; }
public string changed { get; set; }
public string expires { get; set; }
public bool registered { get; set; }
public bool dnssec { get; set; }
public string whoisserver { get; set; }
public List<object> contacts { get; set; }
public Registrar registrar { get; set; }
public List<string> rawdata { get; set; }
public object network { get; set; }
public object exception { get; set; }
public bool parsedContacts { get; set; }
}
public class RootObject
{
public int error { get; set; }
public Response response { get; set; }
}
...
RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;
I'm trying to check if a twitch.tv stream is online or not via c#. Currently I have:
private bool checkStream(String chan)
{
using (var w = new WebClient()) {
String json_data = w.DownloadString("https://api.twitch.tv/kraken/streams/" + chan);
JObject stream = JObject.Parse(json_data);
print(json_data); //just for testing purposes
if (stream["stream"] != null)
{
print("YIPPEE");
}
}
return false;
}
Here's the twitch JSON API for what I'm downloading: https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
As you can see, if a stream is currently offline, the stream field just says null. But obviously, it's still there, so my if(stream["stream"]!=null) check doesn't work. Never used JSON or Newtonsoft's json.net before, so I'm kind of at a loss for what to do. Thanks in advance for any help!
You need to create a class that you can de-serialize the json to. For instance, if you receive json that looks like this
MyJson = {
Prop1 : "Property1",
Prop2 : "Property2"
}
then you'll need to create a class that acts as a contract between your program and the JSON stream.
public class MyJsonClass{
public string Prop1;
public string Prop2;
public MyJsonClass(){
}
}
Now, you can deserialize the json to your C# class and check it for any null values:
// Create a MyJson class instance by deserializing your json string
string myJsonString = ...//get your json string
MyJsonClass deserialized = JsonConvert.DeserializeObject<MyJsonClass>(myJsonString);
if ( deserialized.Prop1 == null )
//etc etc etc
Here's a full processor for that Json response (Disclaimer: I used http://json2csharp.com/ for this code ) :
public class Links
{
public string channel { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string editors { get; set; }
public string subscriptions { get; set; }
public string commercial { get; set; }
public string videos { get; set; }
public string follows { get; set; }
public string self { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public string display_name { get; set; }
public Links3 _links { get; set; }
public List<object> teams { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string logo { get; set; }
public string updated_at { get; set; }
public object mature { get; set; }
public object video_banner { get; set; }
public int _id { get; set; }
public string background { get; set; }
public string banner { get; set; }
public string name { get; set; }
public string url { get; set; }
public string game { get; set; }
}
public class Stream
{
public Links2 _links { get; set; }
public string broadcaster { get; set; }
public string preview { get; set; }
public long _id { get; set; }
public int viewers { get; set; }
public Channel channel { get; set; }
public string name { get; set; }
public string game { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public Stream stream { get; set; }
}
and here's how to use it :
bool StreamOnline = false;
using (var w = new WebClient())
{
var jsonData = w.DownloadData("https://api.twitch.tv/kraken/streams/" + + chan);
var s = new DataContractJsonSerializer(typeof(RootObject));
using (var ms = new MemoryStream(jsonData))
{
var obj = (RootObject)s.ReadObject(ms);
StreamOnline = obj.stream == null;
}
}
return StreamOnline;
Please note that you need to reference System.Runtime.Serialization and add using System.Runtime.Serialization.Json; to use DataContractJsonSerializer. If you don't need every detail just make the stream property of type object (in the RootObject class) and check whether it's null or not.
Have you tried this. The HasValues is a bool property that checks if there are child tokens, if its value is null there will not be any child tokens.
if (stream["stream"].HasValues)
{
print("YIPPEE");
}else
{
print("No Stream");
}