How to read JSON response? - c#

I have an API which validates the cellphones and returns a JSON data. Now I want to read the JSON and show in a table format.
API Call,
protected void CallAPI()
{
WebClient wsClient = new WebClient();
string url = apiUrl;
string response = string.Empty;
string serialkey = txtserialNumber.Text;
WebRequest req = WebRequest.Create(#"https://alt.computechsos.com/api/v1/xx");
req.Method = "POST";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:#password"));
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
WebHeaderCollection header = resp.Headers;
string responseText = string.Empty;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(resp.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
}
The 'responseText' now contains the following JSON
Json returned Response:
{"ios_info":{"serialNumber":"F2LLMBNJXXXQ","imeiNumber":"0138840041323XX","meid":"","iccID":"890141042764009604XX","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.1","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C9XXX","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"product_info":{"serialNumber":"F2LLMBNJXXXQ","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"528","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}
How to read this JSON and show data in table format?

Use Json-Net to deserialize the response. To generate classes, you can use this generator which takes a Json input and outputs the C# classes associated.
//....
var responseObject = JsonConvert.DeserializeObject<RootObject>(responseText);
}
public class IosInfo
{
public string serialNumber { get; set; }
public string imeiNumber { get; set; }
public string meid { get; set; }
public string iccID { get; set; }
public string firstUnbrickDate { get; set; }
public string lastUnbrickDate { get; set; }
public string unbricked { get; set; }
public string unlocked { get; set; }
public string productVersion { get; set; }
public string initialActivationPolicyID { get; set; }
public string initialActivationPolicyDetails { get; set; }
public string appliedActivationPolicyID { get; set; }
public string appliedActivationDetails { get; set; }
public string nextTetherPolicyID { get; set; }
public string nextTetherPolicyDetails { get; set; }
public string macAddress { get; set; }
public string bluetoothMacAddress { get; set; }
public string partDescription { get; set; }
}
public class ConsumerLawInfo
{
public string serviceType { get; set; }
public string popMandatory { get; set; }
public string allowedPartType { get; set; }
}
public class ProductInfo
{
public string serialNumber { get; set; }
public string warrantyStatus { get; set; }
public string coverageEndDate { get; set; }
public string coverageStartDate { get; set; }
public string daysRemaining { get; set; }
public string estimatedPurchaseDate { get; set; }
public string purchaseCountry { get; set; }
public string registrationDate { get; set; }
public string imageURL { get; set; }
public string explodedViewURL { get; set; }
public string manualURL { get; set; }
public string productDescription { get; set; }
public string configDescription { get; set; }
public string slaGroupDescription { get; set; }
public string contractCoverageEndDate { get; set; }
public string contractCoverageStartDate { get; set; }
public string contractType { get; set; }
public string laborCovered { get; set; }
public string limitedWarranty { get; set; }
public string partCovered { get; set; }
public string notes { get; set; }
public string acPlusFlag { get; set; }
public ConsumerLawInfo consumerLawInfo { get; set; }
}
public class RootObject
{
public IosInfo ios_info { get; set; }
public ProductInfo product_info { get; set; }
}

you need to have a class with all the properties which your json string contains , say for example you have that class called Jsondeserial
JsonDeserial obj = JsonConvert.DeserializeObject<JsonDeserial>(jsonstring);
this will convert your json string to that object values

Related

Parse JSon List from webapi [frombody]

I have a json array that comes from webapi [fromBody].
my class is something like this:
public class SalesBOMComponent
{
public string BILLOFMATERIAL { get; set; }
public string BOMITEMNODENUMBER { get; set; }
public string BOMCOMPONENT { get; set; }
public string BOMCOMPONENTDESCRIPTION { get; set; }
public string COMPONENTQUANTITY { get; set; }
public string COMPONENTUOM { get; set; }
public string INDICATORSPAREPART { get;set; }
}
public class SalesBOM
{
public string BILLOFMATERIAL { get; set; }
public string MATERIALPARENT { get; set; }
public string PLANT { get; set; }
public string BOMUSAGE { get; set; }
public string ALTERNATIVEBOM { get; set; }
public string VALIDDATE { get; set; }
public string BASEQTYPARENT { get; set; }
public string BASEUOMPARENT { get; set; }
public string BOMSTATUS { get; set; }
public List<SalesBOMComponent> BOMCOMPONENTS { get; set; }
}
public class Product
{
public string MATERIALPARENT { get; set; }
public string DESCRIPTION { get; set; }
public List<SalesBOM> BOMSALES { get; set; }
}
I would like to get value from BOMCOMPONENT (under class SalesBOMComponent) and Plant (under class SalesBOM).
however, the method read from [fromBody] using c#
public HttpResponseMessage Post([FromBody] Product inputdata)
{
string result = string.Empty;
string currentDate = string.Empty;
string ErrorMessage = string.Empty;
string MaterialParent = string.Empty;
string MaterialDescription = string.Empty;
MaterialParent = inputdata.MATERIALPARENT;
MaterialDescription = inputdata.DESCRIPTION;
how to achieve that?

Deserializing the JSON Objest results in all null fields C#

My jsonResponse is something like this:
{"status":200,"data":{"first_name":"\u062e\u0633","last_name":"\u0635\u062f\u0627","national_code":"1","image_photo":"1.jpg","cellphone":"1234","city":{"id":1,"name":"x","created_at":"2017-02-27 17:54:44","updated_at":"2017-02-27 17:54:44"},"email":"something#gmail.com","even_odd":1,"Register Time":"2018-01-25 10:39:17","is_blocked":false,"receive_regular_offer":"false","level":1,"ride_count":0,"service_type":1,"bank":"\u0645","iban":"xy","card_number":"","holder":"\u062e\u0633","plate_number":"123","vehicle_model":"\u067e\u0698","vehicle_color":"\u062a\u0627\u06a9\u0633","unique_id":592875}}
I have created a class like this:
public class Driver
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public string city { get; set; }
public string email { get; set; }
public string even_odd { get; set; }
public bool is_blocked { get; set; }
public bool receive_regular_offer { get; set; }
public string level { get; set; }
public string ride_count { get; set; }
public string service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public string unique_id { get; set; }
}
and used this:
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Driver snappDriver = js.Deserialize<Driver>(jsonResponse);
But the result is all null!
1.your class should be defined right
example:
void Main()
{
var json =api();
//dynamic
var dynamic_json = JsonConvert.DeserializeObject(json).Dump() as JObject;
//strong type
var strong_Type_json = JsonConvert.DeserializeObject<Driver>(json).Dump() ;
}
string api(){
return #"
{""status"":200,""data"":{""first_name"":""\u062e\u0633"",""last_name"":""\u0635\u062f\u0627"",""national_code"":""1"",""image_photo"":""1.jpg"",""cellphone"":""1234"",""city"":{""id"":1,""name"":""x"",""created_at"":""2017-02-27 17:54:44"",""updated_at"":""2017-02-27 17:54:44""},""email"":""something#gmail.com"",""even_odd"":1,""Register_Time"":""2018-01-25 10:39:17"",""is_blocked"":false,""receive_regular_offer"":""false"",""level"":1,""ride_count"":0,""service_type"":1,""bank"":""\u0645"",""iban"":""xy"",""card_number"":"""",""holder"":""\u062e\u0633"",""plate_number"":""123"",""vehicle_model"":""\u067e\u0698"",""vehicle_color"":""\u062a\u0627\u06a9\u0633"",""unique_id"":592875}}
";
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class Data
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public City city { get; set; }
public string email { get; set; }
public int even_odd { get; set; }
public string Register_Time { get; set; }
public bool is_blocked { get; set; }
public string receive_regular_offer { get; set; }
public int level { get; set; }
public int ride_count { get; set; }
public int service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string plate_number { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public int unique_id { get; set; }
}
public class Driver
{
public int status { get; set; }
public Data data { get; set; }
}
2.json's key Register Time in strong type is invalid name
you can add _ in your json string to solve the problem
Try to create exactly the same class definition as your json has. Your Driver class describes json object's data property.
public class DriverWrapper
{
public string status { get; set; }
public Driver data { get; set; }
}
You have to create another object class that handles status and data property
try this
Create a class Response
class Response{
public int status { get; set;}
public Driver data { get; set;}
}
and do it this way
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Response snappDriver = js.Deserialize<Response>(jsonResponse);

LDAP SearchResponse to Json C#

I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }

Difference JSON deserialisation 'online site' vs 'paste into Visual studio'

I try to generate C# class with JSON datas. This datas are on this site
Method 1 : I used this online builder builder online
Method 2 : I used special paste to JSON into Visual Studio 2015 (like explain here)
Conclusion: not same result! Why?
Result with online site :
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
public class RootObject
{
public string name { get; set; }
public List<string> topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public List<object> callingCodes { get; set; }
public string capital { get; set; }
public List<object> altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public List<object> latlng { get; set; }
public string demonym { get; set; }
public double? area { get; set; }
public double? gini { get; set; }
public List<string> timezones { get; set; }
public List<object> borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public List<string> currencies { get; set; }
public List<object> languages { get; set; }
public Translations translations { get; set; }
}
Result with special paste of Visual Studio :
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public string[] topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public string[] callingCodes { get; set; }
public string capital { get; set; }
public string[] altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public float?[] latlng { get; set; }
public string demonym { get; set; }
public float? area { get; set; }
public float? gini { get; set; }
public string[] timezones { get; set; }
public string[] borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public string[] currencies { get; set; }
public string[] languages { get; set; }
public Translations translations { get; set; }
}
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
Worse! The deserialisation with VS code does'nt work!
Code for deserialise :
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<Rootobject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Rootobject> countries = (IEnumerable<Rootobject>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
Have you an idea of this difference? Bug VS?
In the second example, Visual Studio actually wraps the "root object" with yet another root object that contains an array of Class1.
Since the payload data structure root is an array, not an object, this would appear to be a bug, provided you used the correct payload to generate the structure.
As a result, just replace Rootobject references with Class1.
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(IEnumerable<Class1>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Class1> countries = (IEnumerable<Class1>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
As an aside, you should really switch to a more modern serializer such as Newtonsoft JSON.NET.

Json response with several tables(?)

How do I parse a Json response in form of:
www.extradelar.se/match
If I understand this response right, its an array of three responses, how do I parse them in this case? How do I Deserialize this into my RootObject?
I am not sure if its due to copy paste but the json provided was not valid:
Using http://jsonlint.com/ you can validate an indent your json:
Once you indent, it is easier to look at .
The above JSON is array of array where each one contains an object.
It is a little odd for usual JSON, but maybe you have your own reasons.
Using libraries like JSON.net you can easily parse that data into C# objects.
Hope this helps
EDIT:
POCO Class:
public class RootObject
{
public string match_id { get; set; }
public string no_repick { get; set; }
public string no_agi { get; set; }
public string drp_itm { get; set; }
public string no_timer { get; set; }
public string rev_hs { get; set; }
public string no_swap { get; set; }
public string no_int { get; set; }
public string alt_pick { get; set; }
public string veto { get; set; }
public string shuf { get; set; }
public string no_str { get; set; }
public string no_pups { get; set; }
public string dup_h { get; set; }
public string ap { get; set; }
public string br { get; set; }
public string em { get; set; }
public string cas { get; set; }
public string rs { get; set; }
public string nl { get; set; }
public string officl { get; set; }
public string no_stats { get; set; }
public string ab { get; set; }
public string hardcore { get; set; }
public string dev_heroes { get; set; }
public string verified_only { get; set; }
public string gated { get; set; }
}
JSON.NET
private string getMatchId()
{
using (var webClient = new System.Net.WebClient())
{
const string url = #"http://www.extradelar.se/match";
var json = webClient.DownloadString(url);
var matchen = JsonConvert.DeserializeObject<List<List<RootObject>>>(json);
var matchId = matchen[0][0].match_id;
return matchId;
}
}

Categories

Resources