I am trying to turn a json response back from foursquare into objects. I get something like this back
{
"meta":{
"code":200
},
"response":{
"venues":[
{
"id":"4abfb58ef964a520be9120e3",
"name":"Costco",
"contact":{
"phone":"6045967435",
"formattedPhone":"(604) 596-7435"
},
"location":{
"address":"7423 King George Hwy",
"crossStreet":"btw 76 Avenue & 73A Avenue",
"lat":49.138259617056015,
"lng":-122.84723281860352,
"distance":19000,
"postalCode":"V3W 5A8",
"city":"Surrey",
"state":"BC",
"country":"Canada",
"cc":"CA"
},
"canonicalUrl":"https:\/\/foursquare.com\/v\/costco\/4abfb58ef964a520be9120e3",
"categories":[
{
"id":"4bf58dd8d48988d1f6941735",
"name":"Department Store",
"pluralName":"Department Stores",
"shortName":"Department Store",
"icon":{
"prefix":"https:\/\/foursquare.com\/img\/categories_v2\/shops\/departmentstore_",
"suffix":".png"
},
"primary":true
}
],
"verified":true,
"restricted":true,
"stats":{
"checkinsCount":2038,
"usersCount":533,
"tipCount":12
},
"url":"http:\/\/www.costco.ca",
"specials":{
"count":0,
"items":[
]
},
"hereNow":{
"count":0,
"groups":[
]
},
"referralId":"v-1366316196"
}
]
}
}
I made a class like this
public class Response
{
public string Meta { get; set; }
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
var response = client.Execute<Response>(request);
var test = response.Data;
Yet Venues is always null. I am not sure why though.
You simply need to go a level deeper in the JSON response. One level up from the venues property is the response property, which is not currently represented in your Response class.
You have two ways to solve this.
1) Add another wrapping response object, which contains the missing response property
// this is the new wrapping object
public class FourSquareResponse
{
public string Meta { get; set; }
public VenueResponse Response { get; set; } // previously missing
}
public class VenueResponse
{
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
And executing the request...
var request = new RestRequest(uri);
var response = client.Execute<Response>(request);
2) Ignore the meta property and start parsing at the response property.
*As an aside, it looks like the meta property of the JSON response might be an HTTP status code. If it is and you still need it, RestSharp provides that for you as well (see below).
public class Response
{
public string Meta { get; set; }
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
However, this will require telling RestSharp where to start parsing the response.
var request = new RestRequest(uri)
{
RootElement = "response"
};
var response = client.Execute<Response>(request);
// and the HTTP status (if that's what you need)
response.StatusCode
If i am going in right direction then, ur JSON is not Valid
Error:Strings should be wrapped in double quotes
Get it validated jsonformatter
[UPDATED]
Valid JSON would be like:-
{
"meta": {
"code": 200
},
"notifications":
[
{
"type": "notificationTray",
"item": {
"unreadCount": 0
}
}
],
"response": {
"venues": [
{
"id": "4e15d1348877cd5712112a44",
"name": "The Arena",
"contact": { },
"location": {
"address": "110 Wall Street",
"lat": 40.70432634495503,
"lng": -74.0055421062419,
"distance": 671,
"city": "New York",
"state": "NY",
"country": "United States",
"cc": "US"
},
"canonicalUrl": "https://foursquare.com/v/the-arena/4e15d1348877cd5712112a44",
"categories": [
{
"id": "4bf58dd8d48988d1e4941735",
"name": "Campground",
"pluralName": "Campgrounds",
"shortName": "Campground",
"icon": {
"prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/campground_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 149,
"usersCount": 25,
"tipCount": 4
},
"specials": {
"count": 0,
"items": [ ]
},
"hereNow": {
"count": 0,
"groups": [ ]
},
"referralId": "v-1366314443"
}
]
}
}
JSON deserialization to .NET objects is case sensative. Your property names don't match the JSON tags properly, and that is why when you attempt to deserialize, you are getting back NULL.
Related
Basically I am making an api call I receive the api call in a JSON format and I need to basically filter through the api call to only return the value's for sys_name. I am unsure how to accomplish this as my JsonConvert.DeserializeObject<>() is coming back blank.
{
try
{
using (HttpClient client = GetClient())
{
var response = client.GetAsync("this is the api call but I cleared it as you wont be able to use anyway");
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
var result = await response.Result.Content.ReadAsStringAsync();
Result items = JsonConvert.DeserializeObject<Result>(result);
Console.WriteLine(items.SysName);
return null;
}
};
} catch (Exception ex)
{
_logger.LogWarning(ex, $"Failed to retrieve requested Table |{ex.Message}");
Console.WriteLine(ex.Message);
}
return null;
}
and then I have a wrapper class that I made using jsonutils.com
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysPackage
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysScope
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class Result
{
[JsonProperty("rec_misc")]
public string RecMisc { get; set; }
[JsonProperty("question")]
public Question Question { get; set; }
[JsonProperty("sys_mod_count")]
public string SysModCount { get; set; }
[JsonProperty("sys_updated_on")]
public string SysUpdatedOn { get; set; }
[JsonProperty("sys_tags")]
public string SysTags { get; set; }
[JsonProperty("sys_class_name")]
public string SysClassName { get; set; }
[JsonProperty("published_ref")]
public string PublishedRef { get; set; }
[JsonProperty("sys_id")]
public string SysId { get; set; }
[JsonProperty("sys_package")]
public SysPackage SysPackage { get; set; }
[JsonProperty("inactive")]
public string Inactive { get; set; }
[JsonProperty("sys_update_name")]
public string SysUpdateName { get; set; }
[JsonProperty("sys_updated_by")]
public string SysUpdatedBy { get; set; }
[JsonProperty("sys_created_on")]
public string SysCreatedOn { get; set; }
[JsonProperty("sys_name")]
public string SysName { get; set; }
[JsonProperty("sys_scope")]
public SysScope SysScope { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("sys_created_by")]
public string SysCreatedBy { get; set; }
[JsonProperty("misc")]
public string Misc { get; set; }
[JsonProperty("order")]
public string Order { get; set; }
[JsonProperty("sys_policy")]
public string SysPolicy { get; set; }
}
public class Wrapper
{
[JsonProperty("result")]
public IList<Result> Result { get; set; }
}
}
Showing that items comes up empty
JSON format I had to edit some of the values and obv its way longer but this should give an idea
{
"result": [
{
"rec_misc": "0",
"question": {
"link": "link goes here",
"value": "494a2"
},
"sys_mod_count": "1",
"sys_updated_on": "2021-11-15 17:18:10",
"sys_tags": "",
"sys_class_name": "question_choice",
"published_ref": "",
"sys_id": "",
"sys_package": {
"link": "link goes here",
"value": "global"
},
"inactive": "false",
"sys_update_name": "question_choice_",
"sys_updated_by": "someone ",
"sys_created_on": "2021-11-15 17:17:35",
"sys_name": "BG Info",
"sys_scope": {
"link": "link goes here",
"value": "global"
},
"text": "BG Info",
"value": "BG Info",
"sys_created_by": "someone",
"misc": "0",
"order": "300",
"sys_policy": ""
},
{
"rec_misc": "0",
"question": {
"link": "link goes here",
"value": "5b42"
},
"sys_mod_count": "0",
"sys_updated_on": "2021-04-14 06:56:39",
"sys_tags": "",
"sys_class_name": "question_choice",
"published_ref": "",
"sys_id": "05c2d",
"sys_package": {
"link": "link goes here",
"value": "global"
},
"inactive": "false",
"sys_update_name": "question_choice_",
"sys_updated_by": "someone",
"sys_created_on": "2021-04-14 06:56:39",
"sys_name": "Baseline (Developer Plus Build Mgr)",
"sys_scope": {
"link": "link goes here",
"value": "global"
},
"text": "Baseline (Developer Plus Build Mgr)",
"value": "baseline",
"sys_created_by": "someone",
"misc": "0",
"order": "300",
"sys_policy": ""
},
Use
Wrapper results = JsonConvert.DeserializeObject<Wrapper>(result);
The response is coming as an array so you have to map the data properly.
The problem I am facing is that I am getting 0's for the values I ask for in the JSON.
I recently asked a question here about getting specific values from a JSON array response that come from an API.
Now I have a new JSON response from a different route and in there I want one values and its called EntityId its places in a block of Entity See the code for more details, I would like to grab that from this response and place them in a list or Array because it tells me who submitted the assignment in D2L.
UPDATE- After getting comments from a user I used JSON to C# tool to create the full class with all the values but I still get the values as 0,0,0,0.
Right now I am getting 0,0,0,0 values and not getting the actual values if it's possible I would like to grab the whole block on Entity.
JSON
[
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 27,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-01T15:25:04.130Z",
"Comment": {
"Text": "",
"Html": ""
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 1245,
"FileName": "1.2.10.png",
"Size": 144407
},
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 292,
"FileName": "1.3.8.png",
"Size": 127869
}
]
}
],
"CompletionDate": "2019-08-01T15:25:04.130Z"
},
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 41,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-03T03:31:43.807Z",
"Comment": {
"Text": " \nAlex",
"Html": "<p></p>\n<p>Alex</p>"
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 313,
"FileName": "Capture 1.2.10 Questions.PNG",
"Size": 97722
}
]
}
],
"CompletionDate": "2019-08-03T03:31:43.807Z"
}
]
Classes:
public class Entity
{
public string DisplayName { get; set; }
public int EntityId { get; set; }
public string EntityType { get; set; }
public bool Active { get; set; }
}
public class SubmittedBy
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
}
public class Comment
{
public string Text { get; set; }
public string Html { get; set; }
}
public class File
{
public bool IsRead { get; set; }
public bool IsFlagged { get; set; }
public bool IsDeleted { get; set; }
public int FileId { get; set; }
public string FileName { get; set; }
public int Size { get; set; }
}
public class Submission
{
public int Id { get; set; }
public SubmittedBy SubmittedBy { get; set; }
public DateTime SubmissionDate { get; set; }
public Comment Comment { get; set; }
public IList<File> Files { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
public int Status { get; set; }
public object Feedback { get; set; }
public IList<Submission> Submissions { get; set; }
public DateTime CompletionDate { get; set; }
}
Code:
var request = new RestRequest(string.Format(Link));
request.Method = Method.GET;
authenticator.Authenticate(client, request);
var response = client.Execute(request);
var thisasa = JsonConvert.DeserializeObject<List<Example>>
(response.Content).Select(
o => o.Identifier).ToList();
The Example data model shown in your question already can be used to successfully deserialize the JSON shown. All that's left is to pick out the Entity.EntityId property via a Select:
var thisasa = JsonConvert.DeserializeObject<List<Example>>(response.Content)
.Select(o => o.Entity.EntityId)
.ToList();
Demo fiddle #1 here.
Incidentally, if you only need Entity.EntityId you could simplify your data model as follows:
public class Entity
{
public int EntityId { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
}
Demo fiddle #2 here.
(As an aside, since your Example class corresponds to the documented object Dropbox.EntityDropbox, you might want to rename your type to EntityDropbox for clarity.)
I have defined a model for my input parameter in my HTTP POST method like this
public ActionResult<JObject> Post([FromBody] APIInputObject apiInputObject)
The Model looks like this
public class APIInputObject
{
public string ApiKey { get; set; }
public Brand Brand { get; set; }
public string Query { get; set; }
public string Locale { get; set; } = "SE";
public string UseFormatter { get; set; }
}
The Brand part is further defined like this
public class Consumer
{
public string ConsumerName { get; set; }
public List<Brand> Brands { get; set; }
}
public class Brand
{
public string BrandName { get; set; }
}
The problem is now that when I send JSON is that looks like below I get an error
{
"apiKey": "xxx",
"Brand": "xx",
"query": "showBrand"
}
The error is as follows
{
"errors": {
"Brand": [
"Error converting value \"xx\" to type 'Pim.Models.Brand'. Path 'Brand', line 3, position 17."
]
},
What can I do to fix this error?
Your original JSON formatting is wrong it should be in the following format:
{
"apiKey": "xxx",
"Brand": {
"BrandName": "xx"
},
"query": "showBrand"
}
Bonus help, for your consumer object your json format would be like so:
{
"ConsumerName": "xxx",
"Brands": [{
"BrandName": "xx1"
},
{
"BrandName": "xx2"
}]
}
I am getting the json from zoho. I have a JSON like the following:
{
"response": {
"result": {
"Leads": {
"row": [
{
"no": "1",
"FL": [
{
"content": "1325469000000679001",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
{
"no": "2",
"FL": [
{
"content": "1325469000000659017",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
]
}
},
"uri": "/crm/private/json/Leads/getRecords"
}
}
I am using the following classes:
public class Row
{
[JsonProperty(PropertyName = "row")]
public List<Leads> row { get; set; }
}
public class Leads
{
[JsonProperty(PropertyName = "no")]
public string nbr { get; set; }
[JsonProperty(PropertyName = "FL")]
public List<Lead> FieldValues { get; set; }
}
public class Lead
{
[JsonProperty(PropertyName = "content")]
public string Content { get; set; }
[JsonProperty(PropertyName = "val")]
public string Val { get; set; }
}
I try to deserialize the json and get back nothing:
var mList = JsonConvert.DeserializeObject<IDictionary<string, Row>>(result);
This is the first time working with Json so any help would be appreciated!
Usually when that happens it is because your class model for deserialization is wrong. Rather than trying to hand-craft the classes I like to use http://json2csharp.com. Just plug in your JSON and it gives you the necessary C# classes. In your case it provides the following.
public class FL
{
public string content { get; set; }
public string val { get; set; }
}
public class Row
{
public string no { get; set; }
public List<FL> FL { get; set; }
}
public class Leads
{
public List<Row> row { get; set; }
}
public class Result
{
public Leads Leads { get; set; }
}
public class Response
{
public Result result { get; set; }
public string uri { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
You can then deserialize into RootObject using:
var mList = JsonConvert.DeserializeObject<RootObject>(result);
Feel free to rename RootObject to whatever name you like better.
In windows Phone application i know how to display images forma json data..
Regarding that i followed many articles on parsing the json data..
on the every article they have images in this way
"images" : "http://thegraphicsfairy.com/wp-content/uploads/2013/03/Stock-Image-Bird-Branch-GraphicsFairy1.jpg"
But i have Json Data like
"images" : [
"http://thegraphicsfairy.com/wp-content/uploads/2013/03/Stock-Image-Bird-Branch-GraphicsFairy1.jpg"
]
like that i have many images in my JSON data
"flick" : ["http://thegraphicsfairy.com/wp-content/uploads/2013/05/House-Painter-Man-Image-GraphicsFairy1.jpg"
]
"title" : ["http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg%3Ft%3D20111117074048"
]
So am unable to Parse them i tried with {get,set}
and i followed many articles like
1. Facebook graph.
2. Facebook Feed.
3. Josn list box
4. Nokia Flicker
I want to display them in a Async List Box view
and one more thing i stopped at starting Because in every json data it starts with a JSON Object,.. But MY json data srats with JSON Array inside JSON OBJecet.. aganin Repeat...
This is my JSON data.. and i am getting this data from a server so i may not change the Server
{
"rC": "success",
"SpData": {
"results": [
{
"ndetails": [
{
"laoffers": [],
"offers_count": 0,
"sku": "3246",
"url": "http://www.google.com"
},
{
"laoffers": [
{
"id": "0c4ggUUkY8",
"price": "313.56",
"currency": "USD"
},
{
"id": "5OhvKwkQ",
"price": "311.95",
"currency": "USD"
}
],
"offers_count": 2,
"name": "abc.com",
"url": "http://www.bing.com"
},
{
"laoffers": [
{
"id": "0bZw4cCK",
"price": "339.99",
"currency": "USD"
},
{
"id": "CwEEA",
"shipping": "8.17",
"price": "299.99",
"currency": "USD"
}
],
"o_count": 2,
"name": "aaaa.com",
"recentoffers_count": 1,
"sku": "8567757",
"url": "http://www.avcd.com"
}
],
"model": "818BLK",
"weight": "394625.36",
"price_currency": "USD",
"gtins": [
"044558"
],
"cat_id": "23042",
"features": {
"Condition": "New",
"RAM - Memory": "2 GB - DDR3L SDRAM",
"Rear-facing Camera - Camera": "5 Megapixel"
},
"length": "215.90",
"created_at": 132657,
"variation_id": "2SKEFyM",
"geo": [
"usa"
],
"width": "130.05",
"upc": "84884848",
"ean": "47444",
"category": "Tablets",
"price": "334.99",
"updated_at": 1391388552,
"color": "Black",
"manufacturer": "abc ,amifracture",
"images_total": 1,
"images": [
"http://2.bp.blogspot.com/-AwTiVBnB_e4/T7-Wf4Z9HqI/AAAAAAAAACA/DA2UuBQsQ9g/s1600/funny-animal-pic-images-photos-02.jpg"
],
"brand": "ccc",
"sem3_id": "0iVcESQOy",
"offers_total": 169
}
],
"total_results_count": 1,
"results_count": 1,
"code": "OK",
"offset": 0
}
}
While Parsing at starting i failed Because.. in graph.facebook.com
thy have only two Json arrays..
But i have Json array Inside the Json object or JOSN object inside the json arrya..
and all the images are inside the json array which is inside the results which is inside a empty json object, and that is inside a JSOn array..
i am unable to parse some fields at starting.. and images are inside the json array are not displaying...
So i want to Parse JSON plus images By any json parsing methoid in C#(windows phone)..
and i want to deserilize the data including Images..
like this for example..
private void jsonButton_Click(object sender, RoutedEventArgs e)
{
string fbURL = "http://graph.facebook.com/microsoft";
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += (sndr, eArgs) =>
{
if (!string.IsNullOrEmpty(eArgs.Result))
{
var json = JsonConvert.DeserializeObject<MyPageObject>(eArgs.Result);
this.jAbout.Text = json.about;
this.jCategory.Text = json.category_list[0].name;
this.jFounded.Text = json.founded;
this.jWebsite.Content = json.website;
this.jWebsite.NavigateUri = new Uri(json.website, UriKind.Absolute);
this.jAddress.Text = json.location.street + ", " + json.location.city + ", " + json.location.state;
this.jLikes.Text = json.likes.ToString();
// download cover image
string imageSource = json.cover.source;
this.CoverImage.Source = new BitmapImage(new Uri(imageSource, UriKind.Absolute));
}
};
webClient.DownloadStringAsync(new Uri(fbURL, UriKind.Absolute));
}
At here they have image as normal way.. But i have image inside a JSON array..
and They used Root Object at starting Because they have only one Main JSON arrya.. But i have a many Json arrays and Objects which means [{ or { some data [{ some data... Like that i have..
And at here i want the out put exact like Nokia flicker.... But over there They parsed XML json data.. But i want ONly for JSON data..
Here is a link that convert a json string to respective c# class architecture. Below is the class architecture of your json string.
public class Ndetail
{
public List<object> laoffers { get; set; }
public int offers_count { get; set; }
public string sku { get; set; }
public string url { get; set; }
public string name { get; set; }
public int? o_count { get; set; }
public int? recentoffers_count { get; set; }
}
public class Features
{
public string Condition { get; set; }
public string __invalid_name__RAM - Memory { get; set; }
public string __invalid_name__Rear-facing Camera - Camera { get; set; }
}
public class Result
{
public List<Ndetail> ndetails { get; set; }
public string model { get; set; }
public string weight { get; set; }
public string price_currency { get; set; }
public List<string> gtins { get; set; }
public string cat_id { get; set; }
public Features features { get; set; }
public string length { get; set; }
public int created_at { get; set; }
public string variation_id { get; set; }
public List<string> geo { get; set; }
public string width { get; set; }
public string upc { get; set; }
public string ean { get; set; }
public string category { get; set; }
public string price { get; set; }
public int updated_at { get; set; }
public string color { get; set; }
public string manufacturer { get; set; }
public int images_total { get; set; }
public List<string> images { get; set; }
public string brand { get; set; }
public string sem3_id { get; set; }
public int offers_total { get; set; }
}
public class SpData
{
public List<Result> results { get; set; }
public int total_results_count { get; set; }
public int results_count { get; set; }
public string code { get; set; }
public int offset { get; set; }
}
public class RootObject
{
public string rC { get; set; }
public SpData SpData { get; set; }
}
DataContractJsonSerializer useful with this class architecture to parse a json string.
Below is the sample code.
// json parsing code.
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(Your json string));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject parsedData= dataContractJsonSerializer.ReadObject(memoryStream) as RootObject;
if(parsedData!=null)
{
MessageBox.Show(parsedData.SpData.results.First().ndetails.First().url.ToString());
}