I am trying to consume a REST API via a C# Console Application and I've got as far as getting the webservice to return the JSON file, with the format:
{"status":200,"result":{"postcode":"SW1W0DT","quality":1,"eastings":528813,"northings":178953,"country":"England","nhs_ha":"London","longitude":-0.145828,"latitude":51.494853,"european_electoral_region":"London","primary_care_trust":"Westminster","region":"London","lsoa":"Westminster 023E","msoa":"Westminster 023","incode":"0DT","outcode":"SW1W","parliamentary_constituency":"Cities of London and Westminster","admin_district":"Westminster","parish":"Westminster, unparished area","admin_county":null,"admin_ward":"Warwick","ccg":"NHS Central London (Westminster)","nuts":"Westminster","codes":{"admin_district":"E09000033","admin_county":"E99999999","admin_ward":"E05000647","parish":"E43000236","parliamentary_constituency":"E14000639","ccg":"E38000031","nuts":"UKI32"}}}
I have created a class AddressInfo which is as follows:
public class AddressInfo {
public string postcode { get; set; }
public int quality { get; set; }
public int eastings { get; set; }
public int northings { get; set; }
public string country { get; set; }
public string nhs_ha { get; set; }
public string admin_county { get; set; }
public string admin_district { get; set; }
public string admin_ward { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public string parliamentary_constituency { get; set; }
public string european_electoral_region { get; set; }
public string primary_care_trust { get; set; }
public string region { get; set; }
public string parish { get; set; }
public string lsoa { get; set; }
public string msoa { get; set; }
public string ccg { get; set; }
public string nuts { get; set; }
public object codes { get; set; }
}
The code to call the API and get the values is:
string strJSON = string.Empty;
strJSON = rClient.makeRequest();
Console.Write(strJSON);
AddressInfo AI = new AddressInfo();
AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON);
However, when I debug, AI is returning the values as "NULL".
Thanks
Notice that your JSON has a nested structure. The AddressInfo is contained within its result property, it isn't at the top level.
Your actual class structure to deserialize the entire JSON response should look something like this (I've called the class JsonResponse but you can name it whatever you want):
class JsonResponse{
public int status { get; set; }
public AddressInfo result { get; set; }
}
Then deserialize it like this:
JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON);
AddressInfo addressInfo = res.result;
You're missing the fact that you need an outer class that has the properties int status and AdressInfo result.
You don't need to create a separate class to deserialize the entire response, this can be done dynamically to achieve desired result:
var source = "(your JSON");
dynamic data = JObject.Parse(source);
var d = JsonConvert.SerializeObject(data.result);
AddressInfo account = JsonConvert.DeserializeObject<AddressInfo>(d);
Your JSON is nested. The result is a nested object. That's why you are experiencing this issue.
Related
I have json like this
{
"reader_name":"FX9600EAF871",
"mac_address":"84:24:8D:FC:0E:AD",
"tag_reads":[
{
"epc":"E28068100000003C0A05E3B7",
"antennaPort":"1",
"peakRssi":"-31",
"seenCount":"2458",
"timeStamp":"14/02/2022 22:50:24:356",
"channelIndex":"5"
}
]
}
I try using this code
public class TagRead
{
public string epc { get; set; }
public string pc { get; set; }
public string antennaPort { get; set; }
public string peakRssi { get; set; }
public string seenCount { get; set; }
public string timeStamp { get; set; }
public string phase { get; set; }
public string channelIndex { get; set; }
public string isHeartBeat { get; set; }
}
public class Hdr
{
public string reader_name { get; set; }
public string mac_address { get; set; }
public List<TagRead> tag_reads { get; set; }
}
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
When try to print reader name using
deserialized.reader_name
it gets result FX9600EAF87
but when print
deserialized.tag_reads
it get nothing?
my question is How to get epc & antennaport data?
thank you
Because deserialized.tag_reads is a collection instead of base type or string, you might get the result that you didn't want to get.
How to get epc & antennaport data?
you might try to use deserialized.tag_reads with foreach to iterator the collection then do your logic
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
foreach(var item in deserialized.tag_reads){
//item.epc
//item.antennaPort
}
c# online
I am getting the below JSON in response from a REST API.
{
"data":{
"id":123,
"zoneid":"mydomain.com",
"parent_id":null,
"name":"jaz",
"content":"172.1 6.15.235",
"ttl":60,
"priority":null,
"type":"A",
"regions":[
"global"
],
"system_record":false,
"created_at":"2017-09-28T12:12:17Z",
"updated_at":"2017-09-28T12:12:17Z"
}
}
and trying to resolve using below code but that doesn't result in a correctly deserialized type.
var model = JsonConvert.DeserializeObject<ResponseModel>(response);
below is a class according the field I received in JSON response.
public class ResponseModel
{
public int id { get; set; }
public string zone_id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public int priority { get; set; }
public string type { get; set; }
public string[] regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
What is missing?
You're missing a wrapper class.
public class Wrapper
{
public ResponseModel data {get;set}
}
and then do:
var model = JsonConvert.DeserializeObject<Wrapper>(response).data;
to get the instance of your ResponseModel out the data property.
You can deduct this from your json:
{ "data":
{ "id":123, /*rest omitted */ }
}
The type that will receive this JSON needs to have a property named data. The suggested Wrapper class acts as that type.
According to json2csharp website, your model seems to be incorrect. Try this one :
public class ResponseModel
{
public int id { get; set; }
public string zoneid { get; set; }
public object parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public object priority { get; set; }
public string type { get; set; }
public List<string> regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public ResponseModel data { get; set; }
}
Here a cool trick you can do in Visual Studio 2015-2017 where it generates the the correct class if you just copy the JSON (ctrl + c).
You need to create a new class in visual studio and once inside the class go to Edit menu -> Paste special -> paste JSON As Classes.
Steps to generate json class
This will generate the C# object for that json for you and save you all the hassle :)
Your model does not match your response - it matches the data property. Simply wrap another object round it
public class ResponseData
{
public ResponseModel Data {get; set; {
}
and then
var model = JsonConvert.DeserializeObject<ResponseData>(response);
First time working with JSON and related, I'm trying to get distance/duration of all possible routes from this request: https://maps.googleapis.com/maps/api/directions/json?origin=41.2091585,-8.5763016&destination=41.258913,-8.636942&mode=driving&alternatives=true&avoid=tolls&language=pt-PT&key=AIzaSyDuhdvLAny3MpraXKX-bahkXZJolm7KLbE
I got the following classes using "Paste JSON as Classes" and create one Class for each of the following ones:
public class Rootobject
{
public Geocoded_Waypoints[] geocoded_waypoints { get; set; }
public Route[] routes { get; set; }
public string status { get; set; }
}
public class Route
{
public Bounds bounds { get; set; }
public string copyrights { get; set; }
public Leg[] legs { get; set; }
public Overview_Polyline overview_polyline { get; set; }
public string summary { get; set; }
public object[] warnings { get; set; }
public object[] waypoint_order { get; set; }
}
public class Leg
{
public Distance distance { get; set; }
public Duration duration { get; set; }
public string end_address { get; set; }
public End_Location end_location { get; set; }
public string start_address { get; set; }
public Start_Location start_location { get; set; }
public Step[] steps { get; set; }
public object[] traffic_speed_entry { get; set; }
public Via_Waypoint[] via_waypoint { get; set; }
}
public class Distance
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration
{
public string text { get; set; }
public int value { get; set; }
}
For the query mentioned above I have 3 different routes (aka "legs") and I want to get the distance/duration of each one.
I came up with the following but it's not working.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
Distance t = JsonConvert.DeserializeObject<Distance>(result);
string distance1_Value = t.value;
string distance1_Text = t.text;
Duration d = JsonConvert.DeserializeObject<Duration>(result);
string duration1_Value = d.value;
string duration1_Value = d.text;
}
}
Any help?
PS: If anyone can show me how to iterate throw each "legs" that would be great.
EDIT: Forgot to mention I'm using Newtonsoft.
I found the solution a few days ago...
First, i do the same of you, but still not working for me, so i take a look deep inside the classes auto generated by this tool and notice that some classes was missing the 's' at the end of its names..
Step, where correct name 'Steps'
Leg. correct name 'Legs'
Route. correct name 'Routes'
Do you have to fix this at entire document.
After this, you can convert directly...
Take a look at correct answer: [1]: http://pastie.org/10935748#9
I'm a little stumped on this one. Everything I do to check this out says it is a valid Json array, but JsonConvert.Deserialize says it is an object. Can someone point out what I'm doing wrong?
Code to replicate:
var data = "[{\"User\": {\"Identifier\": \"24233\",\"DisplayName\": \"Commerce Test Student\",\"EmailAddress\": \"email#email.ca\",\"OrgDefinedId\": \"UniqueId1\",\"ProfileBadgeUrl\": null,\"ProfileIdentifier\": \"zzz123\"},\"Role\": {\"Id\": 153,\"Code\": null,\"Name\": \"Commerce Student\"}}]";
var items = JsonConvert.DeserializeObject<List<T>>(data);
Where T is an object that matches the format below:
public class OrgUnitUser
{
public User User { get; set; }
public RoleInfo Role { get; set; }
}
public class User
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
public string EmailAddress { get; set; }
public string OrgDefinedId { get; set; }
public string ProfileBadgeUrl { get; set; }
public string ProfileIdentifier { get; set; }
}
public class RoleInfo
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
It results in an error
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CoverPages.Models.D2L.OrgUnitUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Any/all help is appreciated!
var data = "[{\"User\": {\"Identifier\": \"24233\",\"DisplayName\": \"Commerce Test Student\",\"EmailAddress\": \"email#email.ca\",\"OrgDefinedId\": \"UniqueId1\",\"ProfileBadgeUrl\": null,\"ProfileIdentifier\": \"zzz123\"},\"Role\": {\"Id\": 153,\"Code\": null,\"Name\": \"Commerce Student\"}}]";
public class User
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
public string EmailAddress { get; set; }
public string OrgDefinedId { get; set; }
public object ProfileBadgeUrl { get; set; }
public string ProfileIdentifier { get; set; }
}
public class Role
{
public int Id { get; set; }
public object Code { get; set; }
public string Name { get; set; }
}
public class RootObject
{
public User User { get; set; }
public Role Role { get; set; }
}
var items = JsonConvert.DeserializeObject<List<RootObject>>(data);
or
var items = JsonConvert.DeserializeObject<List<RootObject>>(data)[0];
Try this code I thinks he working good
result:
Thanks to Taras for the confirmation, but there is nothing wrong with the code itself.
When using a generic in JsonConver.Deserialize, it gives the error I listed above, however putting in the actual type of OrgUnitUser into the list, rather than T results in the convert succeeding.
Changing the code from
var items = JsonConvert.DeserializeObject<List<T>>(data);
to
var items = JsonConvert.DeserializeObject<List<OrgUnitUser>>(data);
Fixed the issue
I was hoping someone could help me with a problem serialzing data into a class please?
I need to send the following json string to a webservice:
{ "arrivalAt": "2012-12-24T20:00:00.0000000Z", "pickup":{"streetName":"Amaliegade","houseNumber":"36","zipCode":"1256","city":"Copenhagen K","country":"DK","lat":55.68,"lng":12.59}, "dropoff":{"streetName":"Amaliegade","houseNumber":"36","zipCode":"1256","city":"Copenhagen K","country":"DK","lat":55.68,"lng":12.59}, "vehicleType": "fourSeaterAny", "comments": "Hello" }'
I put this json string into http://json2csharp.com/ and it generated the following class:
public class Pickup
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class Dropoff
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class RootObject
{
public string arrivalAt { get; set; }
public Pickup pickup { get; set; }
public Dropoff dropoff { get; set; }
public string vehicleType { get; set; }
public string comments { get; set; }
}
I have managed to do this before but have never had a situation where is there is a class within a class, so to speak. Meaning the "Pickup" & "DropOff" settings...
I am stuck when i try to work out what to do at this line...
Booking bookingdetails = new ClickATaxi_Classes.Booking(THIS IS WHERE I WILL PUT THE 17 BITS OF INFORMATION BUT HOW?);
I get the feeling there is something i need to do to the class to make it accept arguments but i have no idea where to start and how to send the pickup and dropoff information
can anyone help please?
thanks
First you should refactor that generated code a little bit
public class Location
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class Booking
{
public string arrivalAt { get; set; }
public Location pickup { get; set; }
public Location dropoff { get; set; }
public string vehicleType { get; set; }
public string comments { get; set; }
}
There is no need for two classes that mean the same thing. After that you will just instantiate the booking object.
Booking obj = new Booking { arrivalAt = "ARRIVAL", pickup = new Location { streetName = "", houseNumber = "" ... }, dropoff = new Location { streetName = "", houseNumber = "" ...}, vehicleType = "", comments = "" }
Next you will serialize to a string, I like JSON.NET but you can use any serializer.
If you want to use JSON.NET you can install it via Nuget by following these instructions, next add the using statement to the top of your class that will serialize the object:
using Newtonsoft.Json;
Finally just call JsonConvert
string json = JsonConvert.SerializeObject(product);
Here are some links to other serializers:
http://msdn.microsoft.com/en-us/library/bb410770.aspx
http://www.servicestack.net/docs/text-serializers/json-csv-jsv-serializers
http://code.google.com/p/protobuf-net/
Json.NET. You need a JSON serializer. Just pick one that you like. The 3 that have been listed work great. And make sure you read this article to better understand why you need a JSON serializer.