how to seperate each data from a php post reply result - c#

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

Related

deserialize json list from Rest server c#

Just a little stuck here, I want to grab "notifications"(list) from the json that is sent back to me from the server. Please see below:
{"amountCashback": 0,"amountGratuity": 0, "amountTotal": 0, "notifications":["APPROVED" ],}
notifications being enum;
notifications {
string = ['APPROVED', 'BAD_SWIPE', 'CARD_ERROR', 'CARD_EXPIRED', 'CARD_NOT_SUPPORTED', 'CONNECTING', 'CONNECTION_MADE', 'DECLINED', 'DECLINED_BY_CARD', 'INSERT_CARD', 'PIN_ENTRY', 'PLEASE_WAIT', 'PRESENT_CARD', 'PRESENT_ONLY_ONE_CARD', 'PROCESSING_ERROR', 'REMOVE_CARD', 'RETRYING', 'REQUEST_SENT', 'RE_PRESENT_CARD', 'SIGNATURE_VERIFICATION', 'SIGNATURE_VERIFICATION_PROCESS_COMPLETED', 'SIGNATURE_VERIFICATION_PROCESS_COULD_NOT_BE_COMPLETED', 'SIGNATURE_VERIFICATION_IN_PROGRESS', 'SIGNATURE_VERIFICATION_TIMEOUT', 'TRANSACTION_FINISHED', 'TRANSACTION_STARTED']
Using json to c# I have created the class below
class Polling
{
public int amountBase { get; set; }
public int amountCashback { get; set; }
public int amountGratuity { get; set; }
public int amountTotal { get; set; }
public string authCode { get; set; }
public string cardSchemeName { get; set; }
public string cardHolderVerificationMethod { get; set; }
public string location { get; set; }
public List<string> notifications { get; set; }
public string paymentMethod { get; set; }
public string transactionResult { get; set; }
public DateTime transactionTime { get; set; }
public string transactionType { get; set; }
public string endPoint { get; set; }
public httpVerb httpMethod { get; set; }
public string userPassword { get; set; }
public int sendAmount { get; set; }
public string requestId { get; set; }}
I want to be able to deserialize and grab the notifications to display them on screen. Below I have added the code I am using for this.
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic jsonObjtpi = JsonConvert.DeserializeObject(strResponseValue);
string notifications = jsonObjtpi.notifications.ToString();
return notifications;
}
}
}
}
Thanks guys, really appreciate it
Json can use your strongly typed Polling object, e.g.
Polling polling = JsonConvert.DeserializeObject<Polling>(strResponseValue);
See https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Restsharp Issues Deserialising

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; }
}

Unable To Parse JSON Response in C#

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;

Extract data from Json string

I got a string containing Json. It looks like this:
"status_code":200,
"status_txt":"OK",
"data":
{
"img_name":"D9Y3z.png",
"img_url":"http:\/\/s1.uploads.im\/D9Y3z.png",
"img_view":"http:\/\/uploads.im\/D9Y3z.png",
"img_width":"167",
"img_height":"288",
"img_attr":"width=\"167\" height=\"288\"",
"img_size":"36.1 KB",
"img_bytes":36981,
"thumb_url":"http:\/\/s1.uploads.im\/t\/D9Y3z.png",
"thumb_width":360,
"thumb_height":360,
"source":"http:\/\/www.google.com\/images\/srpr\/nav_logo66.png",
"resized":"0",
"delete_key":"df149b075ab68c38"
}
I am trying to get a hold of the "img_url". I have Json.NET installed and I´ve found similar questions here..
for example something like this:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");
In my case I changed ("People[0].Name") to ("img_url"),("img_url[0]) etc..no luck
This is my code now:
public string tempJson { get; set; }
public ActionResult SaveUploadedFile(string test)
{
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
Do I have to do something with the string before I can extract the value?
Thanks!
img_url is not a property of root object - it's a property of data object:
var obj = JObject.Parse(json);
var url = (string)obj["data"]["img_url"]; // http://s1.uploads.im/D9Y3z.png
Another option:
var url = (string)obj.SelectToken("data.img_url");
With help of this site
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.data.img_url);
public class Data
{
public string img_name { get; set; }
public string img_url { get; set; }
public string img_view { get; set; }
public string img_width { get; set; }
public string img_height { get; set; }
public string img_attr { get; set; }
public string img_size { get; set; }
public int img_bytes { get; set; }
public string thumb_url { get; set; }
public int thumb_width { get; set; }
public int thumb_height { get; set; }
public string source { get; set; }
public string resized { get; set; }
public string delete_key { get; set; }
}
public class RootObject
{
public int status_code { get; set; }
public string status_txt { get; set; }
public Data data { get; set; }
}
You can also do the same thing with the use of dynamic keyword (without declaring above classes)
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.data.img_url);

ASP.NET Web API - How to deserialize a JSON

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.

Categories