C# JSON to each item - c#

I'm trying to get some information from a JSON link and display it to the user in a friendly way. I'm tried everything and can't seem to get my head around this.Basically I want to show the user
ID = somevalue
GUID = SomeValue
Name = Somevalue
etc.
After I got my JSON I went to json2csharp and got my classes as shown below:
public class Computer
{
public string ID { get; set; }
public string GUID { get; set; }
public string name { get; set; }
public string type { get; set; }
public string entity { get; set; }
public string serial { get; set; }
public string uuid { get; set; }
public string inventorynumber { get; set; }
public string status { get; set; }
public string site { get; set; }
public string location { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string owner { get; set; }
public string lastuser { get; set; }
public string domain { get; set; }
public string os { get; set; }
public string servicepack { get; set; }
public string osversion { get; set; }
}
public class Data
{
public List<Computer> computers { get; set; }
}
public class RootObject
{
public string state { get; set; }
public Data data { get; set; }
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.xxx/?xxx=xxx&format=json ");
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var rawJson = reader.ReadToEnd();
RootObject rootResult = JsonConvert.DeserializeObject<RootObject>(rawJson);
Console.Write();
Console.ReadKey();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
Console.WriteLine(errorText);
}
throw;
}
with this code if I do
Console.WriteLine(rootResult.state);
I get my "Success" value. But I can't find a way to actually get the data I have under "Computer"
Can anyone show me a way what I'm doing wrong?
I also tried to follow the similar questions but they all seem to be different since my JSON format is a little different.
Thanks in advance.

What happens if you simply iterate over your rootResult.data.computers, which should be a list of computers?
if(rootResult.data != null)
{
foreach (var computer in rootResult.data.computers)
{
Console.WriteLine(computer.ID);
Console.WriteLine(computer.GUID);
// etc for all properties
}
}

Related

Null when trying to load a JSON from Root PCL Xamarin

Hi when trying to load a JSON file from the root of my PCL it breaks on this line Using (var reader = new StreamReader(stream)) and says its null.
here is the full method for loadJson()
public void LoadJson()
{
//Loads the JSON File in the Solution and Finds Correct ID of Accordion Hopefully!!
var assembly = typeof(App).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("MCETimeTest.TimeSheet.json");
string jsonString = "";
using (var reader = new StreamReader(stream))
{
jsonString = reader.ReadToEnd();
};
uoObj = JsonConvert.DeserializeObject<RootObject>(jsonString);
}
Edit: when stepping through the code stream is always null
and my classes for my json are:
//JSON Classes
public class RootObject
{
public List<LineItem> LineItems { get; set; }
}
public class Checks
{
public DateTime TheDate { get; set; }
public string JobNumber { get; set; }
public string CustomerName { get; set; }
public TimeSpan On1 { get; set; }
public TimeSpan Off1 { get; set; }
public TimeSpan On2 { get; set; }
public TimeSpan Off2 { get; set; }
public string Description { get; set; }
public string SingleHours { get; set; }
public string TimeHalfHours { get; set; }
public string DoubleHours { get; set; }
}
public class LineItem
{
public string Id { get; set; }
public string Customer { get; set; }
public List<Checks> Checks { get; set; }
}
Also looking over the solution it turns out that the JSON File in the root was not an Embedded Resource. After changing it, it works! sorry for the hassle!

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

how to seperate each data from a php post reply result

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

Facing issue while deserializing xml Http Response

I am trying to deserialize the HTTPresponse which is in xml format to an Object.
XML Response:
<?xml version="1.0" encoding="utf-8" ?>
- <NPIList>
- <NPI>
<NPI>1003000118</NPI>
<EntityType>Organization</EntityType>
<IsOrgSubpart>N</IsOrgSubpart>
<OrgName>STEVEN ENGEL PEDIATRICS</OrgName>
<FirstLineMailingAddress>1700 NEUSE BLVD</FirstLineMailingAddress>
<MailingAddressCityName>NEW BERN</MailingAddressCityName>
<MailingAddressStateName>NC</MailingAddressStateName>
<MailingAddressPostalCode>28560-2304</MailingAddressPostalCode>
<MailingAddressCountryCode>US</MailingAddressCountryCode>
<MailingAddressTelephoneNumber>252-637-3799</MailingAddressTelephoneNumber>
<MailingAddressFaxNumber>252-633-0944</MailingAddressFaxNumber>
<FirstLinePracticeLocationAddress>1700 NEUSE BLVD</FirstLinePracticeLocationAddress>
<PracticeLocationAddressCityName>NEW BERN</PracticeLocationAddressCityName>
</NPI>
</NPIList>
My code to retrieve the xmlhttp response and deserialize as follows:
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
Stream respStream = response.GetResponseStream();
XmlSerializer ser = new XmlSerializer(typeof(NPIList));
var resp = (NPIList)ser.Deserialize(respStream);
response.Close();
}
I have created my object class
public class NPIList
{
public List<NPIObj> NPI { get; set; }
}
I am getting the count as zero for the variable "resp".
Here is my NPIObj class:
public class NPIObj
{
public string EntityType { get; set; }
public string FirstLineMailingAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MailingAddressCityName { get; set; }
public string MailingAddressCountryCode { get; set; }
public string MailingAddressPostalCode { get; set; }
public string MailingAddressStateName { get; set; }
public string MiddleName { get; set; }
public string NamePrefix { get; set; }
public string NPI { get; set; }
public string OrgName { get; set; }
public string SecondLineMailingAddress { get; set; }
}
Can anyone please help me what could be the issue.
Try adding the XmlElement attribute like:
public class NPIList
{
[XmlElement("NPI")]
public List<NPIObj> NPI { 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;

Categories