Nested JSON failed to deserialize - c#

This is the link for my nested JSON
: -
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=AIzaSyDk8ZfHO__XrYfDGi9RnFA_WxlVmRW5HMI
i have generated a model class which has to give me the list of names , later i populate them in a RecyclerView.
using System;
using System.Collections.Generic;
namespace newApp.Model
{
public class Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Geometry
{
public Location location { get; set; }
public Viewport viewport { get; set; }
}
public class OpeningHours
{
public bool open_now { get; set; }
}
public class Photo
{
public int height { get; set; }
public List<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public class PlusCode
{
public string compound_code { get; set; }
public string global_code { get; set; }
}
public class Result
{
public Geometry geometry { get; set; }
public string icon { get; set; }
public string id { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public List<Photo> photos { get; set; }
public string place_id { get; set; }
public PlusCode plus_code { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public List<string> types { get; set; }
public string vicinity { get; set; }
}
public class RootObject
{
public List<object> html_attributions { get; set; }
public List<Result> results { get; set; }
public string status { get; set; }
}
}
Then , in this method i tried to deserialize the data , i want to get a list of icon, name , id and location.
This is the method i initially have :
public async void getData()
{
var content = await _client.GetStringAsync(URL);
var n = JsonConvert.DeserializeObject<List<List<Result>>>(content);
Debug.WriteLine("Output ", n);
}

Try to deserialize to the RootObject class directly:
JsonConvert.DeserializeObject<RootObject>(content);
And then retrieve all data you need using LINQ.
Declare ResultHeadInfo class which will contain fields you need:
public class ResultHeadInfo
{
public Location Location { get; set; }
public string Name { get; set; }
public string Id { get; set; }
public string Icon { get; set; }
}
Then write LINQ query to get data:
var root = JsonConvert.DeserializeObject<RootObject>(content);
List<ResultHeadInfo> infoList = root.results.Select(x => new ResultHeadInfo {
Location = x.geometry.location,
Name = x.name,
Id = x.id,
Icon = x.icon
}).ToList();
By the way, you can use just Location object instead of Northest and Southwest as they are identical.
public class Viewport
{
public Location northeast { get; set; }
public Location southwest { get; set; }
}

In addition to the other answer, don't forget you can use attributes to identify the fields but keep the property names consistent with the usual naming conventions:
public partial class Viewport
{
[JsonProperty("northeast")]
public Location Northeast { get; set; }
[JsonProperty("southwest")]
public Location Southwest { get; set; }
}
I created those same classes recently for my project, and used quicktype.io to generate them. Much better output than the usual 'Paste Special' built into VS.

Related

Getting specific data from JSON Model

Here is my JSON model for trying to get info from Google Maps API. I am trying to get the "name" and "vicinity" from the "Result "class, but am having trouble with getting the data values from the IList, preferably i would like all the name and vicinity attributes to be returned as a string. Anyone got any ideas? Not familiar with using IList's on projects.
public record Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public record Geometry
{
public Location location { get; set; }
public Viewport viewport { get; set; }
}
public record OpeningHours
{
public bool? open_now { get; set; }
}
public record Photo
{
public int height { get; set; }
public IList<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public record PlusCode
{
public string compound_code { get; set; }
public string global_code { get; set; }
}
public record Result
{
public string business_status { get; set; }
public Geometry geometry { get; set; }
public string icon { get; set; }
public string icon_background_color { get; set; }
public string icon_mask_base_uri { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public IList<Photo> photos { get; set; }
public string place_id { get; set; }
public PlusCode plus_code { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public IList<string> types { get; set; }
public int user_ratings_total { get; set; }
public string vicinity { get; set; }
}
public record ResourceData
{
public IList<object> html_attributions { get; set; }
public IList<Result> results { get; set; }
public string status { get; set; }
}
public record record_GooglePlacesAPI
{
public DateTime TimeCreated { get; set; } = DateTime.UtcNow;
public ResourceData resourceData { get; set; }
}
Try running a simple LINQ query on the data returned from google API like the following
//string holding google api response
string googleResponse = string.Empty;
var googleapi = JsonConvert.DeserializeObject<record_GooglePlacesAPI>(googleResponse);
//Linq query that returns list of names and vicinities
List<string> vicinities = googleapi.resourceData.results.Select(r => r.vicinity).ToList();
List<string> names = googleapi.resourceData.results.Select(r => r.name).ToList();
it should return you a list of strings holding names and viciniteis

Json Deserialization | Cannot Deserialize Current Json

I have below Json -
{"property_id":"53863730","name":"Hayat Elhamra","address":{"line_1":"Jeddah","city":"Jeddah","state_province_name":"Jeddah","postal_code":"23212","country_code":"SA","obfuscation_required":false,"localized":{"links":{"ar-SA":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=ar-SA&property_id=53863730&include=address"}}}},"location":{"coordinates":{"latitude":21.520902,"longitude":39.158265}},"phone":"20-01145772035","category":{"id":"16","name":"Apartment"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":true},"dates":{"added":"2020-06-10T23:03:21.345Z","updated":"2020-06-10T23:03:23.701Z"},"chain":{"id":"0","name":"Independent"},"brand":{"id":"0","name":"Independent"}}
{"property_id":"53183065","name":"Carefully Furnished Bungalow With 2 Bathrooms, 7km From Pula","address":{"line_1":"1 x M 90,3","line_2":"PRIVATE_VACATION_HOME 3","city":"Fazana","state_province_name":"Istria (county)","postal_code":"52212","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53183065&include=address"}}}},"ratings":{"property":{"rating":"3.0","type":"Star"}},"location":{"coordinates":{"latitude":44.93,"longitude":13.8}},"phone":"410442743080","category":{"id":"17","name":"Private vacation home"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:06:42.861Z","updated":"2020-05-18T21:57:39.242Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 4","value":"4"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 2","value":"2"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
{"property_id":"53182898","name":"Snug Cottage in Pašman With Roofed Terrace","address":{"line_1":"Pasman","city":"Pasman","state_province_name":"Zadar","postal_code":"23260","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53182898&include=address"}}}},"ratings":{"property":{"rating":"1.0","type":"Star"}},"location":{"coordinates":{"latitude":43.891571,"longitude":15.423619}},"phone":"410442743080","category":{"id":"11","name":"Cottage"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:13:49.155Z","updated":"2020-05-27T21:02:31.808Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 5","value":"5"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 1","value":"1"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
For this I have created below class structure -
public class Property
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public Business_Model business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Links
{
public ArSA arSA { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Coordinates
{
public float latitude { get; set; }
public float longitude { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class Business_Model
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
I have below code where I am getting error -
using (StreamReader streamReader = new StreamReader("d://propertycontent.expediacollect.en-US.json"))
{
using (var json = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
var properties= (List<Property>)serializer.Deserialize(json, typeof(List<Property>));
}
}
Error -
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Property]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'property_id', line 1, position 15.'
It is not deserializing because it is not valid json. To make it valid, and to make it a List<Property> add [ to the beginning of the json and ] to the end of the json. Just enclose the json in [ ... ] to make it valid and it will deserialize assuming the rest of it is valid and is not missing any commas or brackets.
try this, you will have to install NewtonsoftJson. It was tested using Visual Studio and Postman and works properly.
var jsonOrig= ...your json
var json = JsonConvert.SerializeObject(jsonOrig);
var jsonObj = JsonConvert.DeserializeObject<DataRoot>(json);
classes
public class DataRoot
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public BusinessModel business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Links
{
[JsonProperty("ar-SA")]
public ArSA ArSA { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Coordinates
{
public double latitude { get; set; }
public double longitude { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class BusinessModel
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
`````

json feed as a datasource in SSIS

I am trying to deserialize a json feed from openweathermap.org api. After a lot of tries all, using script transformation task, I get is errors and even different ones. Based on the below classes generated by JSON, how I should write the for each statements (as class Weather and Main are part of class RootObject)?
I can get even XML data from api, instead of JSON. Would it be easier to implement the process?
I am not asking for the answer, just a push to start.
JSON:
{
"coord":{
"lon":-122.08,
"lat":37.39
},
"weather":[
{
"id":741,
"main":"Fog",
"description":"fog",
"icon":"50n"
}
],
"base":"stations",
"main":{
"temp":286.14,
"pressure":1022,
"humidity":82,
"temp_min":285.15,
"temp_max":287.15
},
"visibility":16093,
"wind":{
"speed":1.11,
"deg":13.5055
},
"clouds":{
"all":1
},
"dt":1479110160,
"sys":{
"type":1,
"id":397,
"message":0.1452,
"country":"US",
"sunrise":1479134859,
"sunset":1479171466
},
"id":5375480,
"name":"Mountain View",
"cod":200
}
Class:
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}

GeoJson c# example parse countries in the world and generate Geojson for each country

Looking for an example of how to parse / deserialize Geojson files using geojson.net. for some reason there are no examples of how to use the geojson.net package.
I would like to use this on my site with the google maps api. currently I use polygon shapes but want to move towards using geojson objects for the layers as this seems to be a better format.
using c# I would like to serialize Geojson, select specific country borders and generate a new geojson file that can be references and added to google maps as a layer.
to test this I created a colsole app to try to deserilaize the GeoJson, this does not work (please could you give me some direction on the correct way to deserialize Geojson ?)
static void Main(string[] args)
{
string Jsonstring = File.ReadAllText("c:/worldborders.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
List<GeoJsonProperties> ns = (List<GeoJsonProperties>)ser.Deserialize(Jsonstring, typeof(List<GeoJsonProperties>));
?ns is Empty?
}
I created a class for the geojson file using the online generator http://json2csharp.com/ (I had thought that GeoJson.net would include the class as its a standard) , GeoJsonProperties,
public class GeoJsonProperties
{
public int scalerank { get; set; }
public string featurecla { get; set; }
public double labelrank { get; set; }
public string sovereignt { get; set; }
public string sov_a3 { get; set; }
public double adm0_dif { get; set; }
public double level { get; set; }
public string type { get; set; }
public string admin { get; set; }
public string adm0_a3 { get; set; }
public double geou_dif { get; set; }
public string geounit { get; set; }
public string gu_a3 { get; set; }
public double su_dif { get; set; }
public string subunit { get; set; }
public string su_a3 { get; set; }
public double brk_diff { get; set; }
public string name { get; set; }
public string name_long { get; set; }
public string brk_a3 { get; set; }
public string brk_name { get; set; }
public object brk_group { get; set; }
public string abbrev { get; set; }
public string postal { get; set; }
public string formal_en { get; set; }
public string formal_fr { get; set; }
public string note_adm0 { get; set; }
public string note_brk { get; set; }
public string name_sort { get; set; }
public string name_alt { get; set; }
public double mapcolor7 { get; set; }
public double mapcolor8 { get; set; }
public double mapcolor9 { get; set; }
public double mapcolor13 { get; set; }
public double pop_est { get; set; }
public double gdp_md_est { get; set; }
public double pop_year { get; set; }
public double lastcensus { get; set; }
public double gdp_year { get; set; }
public string economy { get; set; }
public string income_grp { get; set; }
public double wikipedia { get; set; }
public object fips_10 { get; set; }
public string iso_a2 { get; set; }
public string iso_a3 { get; set; }
public string iso_n3 { get; set; }
public string un_a3 { get; set; }
public string wb_a2 { get; set; }
public string wb_a3 { get; set; }
public double woe_id { get; set; }
public string adm0_a3_is { get; set; }
public string adm0_a3_us { get; set; }
public double adm0_a3_un { get; set; }
public double adm0_a3_wb { get; set; }
public string continent { get; set; }
public string region_un { get; set; }
public string subregion { get; set; }
public string region_wb { get; set; }
public double name_len { get; set; }
public double long_len { get; set; }
public double abbrev_len { get; set; }
public double tiny { get; set; }
public double homepart { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<List<List<object>>> coordinates { get; set; }
}
public class Feature
{
public string type { get; set; }
public GeoJsonProperties properties { get; set; }
public Geometry geometry { get; set; }
}
public class RootObject
{
public string type { get; set; }
public List<Feature> features { get; set; }
}
}
GeoJSON.Net works with Newtonsoft.Json. you can deserialize the same way you would using that library.
var geoJsonObject = JsonConvert.DeserializeObject<Point>(json);
For deserializing a FeatureCollection object (like the one you mention in the question) using the GeoJSON.Net library use the following code :
var collection = JsonConvert.DeserializeObject<FeatureCollection>(json);

get data from json c#

I have a problem I want to get data from Json, and the data
successfully gets from the json to the variable json but when I want to send the data to WeatherData it send me a zero value.
I have one class that cald "WeatherData" and I want to send to data from the json (that existing a class "jsonParse") to this class.
jsonParse
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
using System.IO;
namespace weather
{
public class jsonParse : Ijson
{
private string urlAdd;
public jsonParse(string _url)
{
if (_url == null)
{
//throw exption
}
else
urlAdd = _url;
}
public WeatherData parse()
{
//string json = new WebClient().DownloadString(urlAdd);
//var obj = JsonConvert.DeserializeObject<WeatherData>(json);
//Console.WriteLine(obj.temp);
// WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
WebClient n = new WebClient();
var json = n.DownloadString(urlAdd);
string valueOriginal = Convert.ToString(json);
WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
Console.WriteLine(m);
return m;
}
}
}
WeatherData
namespace weather
{
public class WeatherData
{
public WeatherData(double _temp, double _minTemp, double _maxTemp )
{
temp = _temp;
minTemp = _minTemp;
maxTemp = _maxTemp;
}
public double temp { get; set; }
public double minTemp { get; set; }
public double maxTemp { get; set; }
public override string ToString()
{
return "the weather:" + temp + "minTemp is:" + minTemp + "maxTemp:" + maxTemp;
}
}
}
json
{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}
If you only care about the weather part of the json, try this -
var o = (JArray)JObject.Parse(jsonString)["weather"];
foreach(JToken item in o)
{
Console.WriteLine(((JValue)item["id"]).Value);
Console.WriteLine(((JValue)item["main"]).Value);
Console.WriteLine(((JValue)item["description"]).Value);
Console.WriteLine(((JValue)item["icon"]).Value);
}
First object in json is coord, don't see that in your model.
You should change your JsonModel to deserialize. From c# class generator:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int humidity { get; set; }
public int pressure { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
Where RootObject is your JsonConvert.DeserializeObject(json);
So you can change class names as you like.
Simply you cannot Deserialize a json object to a non-matching class object. So make sure you have a model object that have atleast all the properties that JSON object have.
In this case you would need following classes that are generated from your JSON object:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int humidity { get; set; }
public int pressure { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class ParentModel
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
ParentModel m = JsonConvert.DeserializeObject<ParentModel>(json);
Hope this helps.

Categories

Resources