Get values from string response c# - c#

This json is from a HTTPresponse from google API:
{
"results": [
{
"address_components": [
{
"long_name": "Europe",
"short_name": "Europe",
"types": [
"continent",
"establishment",
"natural_feature"
]
}
],
"formatted_address": "Europe",
"geometry": {
"bounds": {
"northeast": {
"lat": 82.1673907,
"lng": 74.3555001
},
"southwest": {
"lat": 34.5428,
"lng": -31.4647999
}
},
"location": {
"lat": 54.5259614,
"lng": 15.2551187
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 65,
"lng": 55
},
"southwest": {
"lat": 34,
"lng": -11
}
}
},
"place_id": "ChIJhdqtz4aI7UYRefD8s-aZ73I",
"types": [
"continent",
"establishment",
"natural_feature"
]
}
],
"status": "OK"
}
I built a list class:
public class geocode {
public class AddressComponent
{
public string long_name { get; set; }
public string short_name { get; set; }
public List<string> types { 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 Bounds
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Northeast2
{
public int lat { get; set; }
public int lng { get; set; }
}
public class Southwest2
{
public int lat { get; set; }
public int lng { get; set; }
}
public class Viewport
{
public Northeast2 northeast { get; set; }
public Southwest2 southwest { get; set; }
}
public class Geometry
{
public Bounds bounds { get; set; }
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
}
public class Result
{
public List<AddressComponent> address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public List<string> types { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
public string status { get; set; }
}
}
And this is far I get:
nombrePapa = nombrePapa.ToUpper();
var resultadoGeocoding = ggo.geocoding(nombrePapa);
//var result = JsonConvert.DeserializeObject<listas.geocode.Result>(resultadoGeocoding);
List<listas.geocode> lista = JsonConvert.DeserializeObject<List<listas.geocode>>(resultadoGeocoding);
But this deserialization stuck me on:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Models.listas+geocode]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I'm missing something?

What the error is telling you is that in order to correctly deserialize your JSON into a List<listas.geocode>, you'd need your JSON to represent an array. What you are giving the deserializer instead is an object, with two properties, results and status.
I'm guessing you used json2csharp to get your classes, since you already have a class for the root object. You just forgot to use it
To deserialize the response you need to do:
var response = JsonConvert.DeserializeObject<RootObject>(resultadoGeocoding);
var lista = response.Results;
Additional note: For status, you can use a string (easiest option), or you can use an enum as detailed here.

Related

How do I parse Openweather One Call in C#?

I have successfully parsed Openweather's 'Current Weather Data' using Json, but I'm having a problem with 'One Call'. It returns the data arranged a little differently. I can pull out everything except the 'weather' list. The class I created for it returns null values.
{
"lat": 41.9585,
"lon": -78.1892,
"timezone": "America/New_York",
"timezone_offset": -14400,
"current": {
"dt": 1652559634,
"sunrise": 1652522008,
"sunset": 1652574293,
"temp": 74.53,
"feels_like": 75.11,
"pressure": 1014,
"humidity": 73,
"dew_point": 65.32,
"uvi": 2.37,
"clouds": 100,
"visibility": 10000,
"wind_speed": 7.47,
"wind_deg": 173,
"wind_gust": 10.63,
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
]
}
}
string url = string.Format("https://api.openweathermap.org/data/2.5/onecall?lat={0}&lon={1}&exclude=minutely,hourly,daily&appid={2}&units=imperial", 41.958496166, -78.18916591, APIKey);
string jason = web.DownloadString(url);
WeatherInfo.root info = JsonConvert.DeserializeObject<WeatherInfo.root>(jason);
public static class WeatherInfo
{
public class current
{
public double dt { get; set; }
public double sunrise { get; set; }
public double sunset { get; set; }
public double temp { get; set; }
public double pressure { get; set; }
public double humidity { get; set; }
public double dew_point { get; set; }
public double uvi { get; set; }
public double clouds { get; set; }
public double visibility { get; set; }
public double wind_speed { get; set; }
public double wind_deg { get; set; }
public double wind_gust { get; set; }
}
public class weather
{
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class root
{
public current current { get; set; }
public List<weather> weather { get; set; }
}
}

Why is my inner array not being deserialized?

I have some JSON which I'd like to deserialize into Objects.
I'm trying to do it like this, but I only get some of the JSON deserialized and the vin and vout JSON are either 0s or nulls. What am I doing wrong?
Transaction t = JsonConvert.DeserializeObject<RPCResponse<Transaction>>(json).result;
JSON:
{
"result": {
"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000",
"txid": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"hash": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"size": 134,
"version": 1,
"locktime": 0,
"vin": [
{
"coinbase": "04ffff001d0104",
"sequence": 4294967295
}
],
"vout": [
{
"value": 50.00000000,
"n": 0,
"scriptPubKey": {
"asm": "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG",
"hex": "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac",
"reqSigs": 1,
"type": "pubkey",
"addresses": [
"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"
]
}
}
],
"blockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"confirmations": 563356,
"time": 1231469665,
"blocktime": 1231469665
},
"error": null,
"id": "getrawtransaction"
}
The output in the debugger looks like this:
My Classes look like this:
public class RPCResponse<T>
{
public T result { get; set; }
public string error { get; set; }
public string id { get; set; }
}
public class Transaction
{
public string TxId { get; set; }
public long Size { get; set; }
public long Version { get; set; }
public long LockTime { get; set; }
public TransactionInputCoinbase[] Vin { get; set; }
public TransactionOutput[] Vout { get; set; }
public string BlockHash { get; set; }
public long Time { get; set; }
}
public class TransactionInputCoinbase
{
string Coinbase { get; set; }
string Sequence { get; set; }
}
public class TransactionOutput
{
decimal Value { get; set; }
int N { get; set; }
ScriptPubKey ScriptPubKey { get; set; }
}
public class ScriptPubKey
{
string Asm { get; set; }
string Hex { get; set; }
long ReqSigs { get; set; }
string Type { get; set; }
string[] Addresses { get; set; }
}
The lack of public properties on the said objects
For example
public class TransactionInputCoinbase
{
string Coinbase { get; set; } //<--NOT PUBLIC
string Sequence { get; set; } //<--NOT PUBLIC
}
means those properties will never be set when initialized via deserialization.
The same goes for TransactionOutput and ScriptPubKey based on the code originally provided.

Part of JSON returned by API is serialised by JSON.NET but not all

I imagine this is more of a problem with my code rather than a problem with JSON.NET, but I'm not sure where I'm going wrong.
I have the following class below which is being used to serialise the json data found at this link: https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
To construct this class I used a JSON to C# generator found on google.
Also below are the methods I use to pull and serialise the JSON data into a WeatherData object.
private string GetJsonFromWeb(string resource, string city)
{
var request = new RestRequest(resource, Method.GET);
request.AddParameter("q", city);
request.AddParameter("APPID", "af5e6fd579e0ddb303afc1774487c77b");
var fullUrl = client.BuildUri(request);
Console.WriteLine("Full URL: " + fullUrl.AbsoluteUri);
var response = client.Execute(request);
string json = response.Content;
return json;
}
private WeatherData SerializeJsonToWeatherData(string json)
{
WeatherData weatherData = JsonConvert.DeserializeObject<WeatherData>(json);
return weatherData;
}
These methods work successfully, as the JSON data can be used later in the application to display information within the GUI. However the MainData part of the JSON data is set to null after the JSON is pulled from the API.
class WeatherData
{
public Coord Coord { get; set; }
public List<Weather> Weather { get; set; }
public string Base { get; set; }
public MainData MainData { 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; }
}
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 MainData
{
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 int 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; }
}
Sample JSON from above API
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}
The JSON property is called main not mainData. JSON.Net can't find a property called mainData ans thus does not populate the MainData property of your POCOs

Deserializing an array of different object types

Using the Json.NET library, I'm having trouble deserializing some json returned as an array. The json is an array containing some paging information as an object and array of country objects. Here's a sample of the returned json:
[
{
"page": 1,
"pages": 6,
"per_page": "50",
"total": 262
},
[
{
"id": "ABW",
"iso2Code": "AW",
"name": "Aruba",
"region": {
"id": "LCN",
"value": "Latin America & Caribbean (all income levels)"
},
"adminregion": {
"id": "",
"value": ""
},
"incomeLevel": {
"id": "NOC",
"value": "High income: nonOECD"
},
"lendingType": {
"id": "LNX",
"value": "Not classified"
},
"capitalCity": "Oranjestad",
"longitude": "-70.0167",
"latitude": "12.5167"
}
]
]
I am attempting to deserialize to the following types:
class CountriesQueryResults
{
public PagingInfo PageInfo { get; set; }
public List<CountryInfo> Countries { get; set; }
}
class PagingInfo
{
public int Page { get; set; }
public int Pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int Total { get; set; }
}
class CountryInfo
{
public string Id { get; set; }
public string Iso2Code { get; set; }
public string Name { get; set; }
public string Longitude { get; set; }
public string Latitude { get; set; }
public string CapitalCity { get; set; }
public CompactIdentifier Region { get; set; }
public CompactIdentifier AdminRegion { get; set; }
public CompactIdentifier IncomeLevel { get; set; }
public CompactIdentifier LendingType { get; set; }
}
class CompactIdentifier
{
public string Id { get; set; }
public string Value { get; set; }
}
I am calling DeserializeObject as so:
var data = JsonConvert.DeserializeObject<List<CountriesQueryResults>>(response);
I am getting the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'CountriesQueryResults' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I have been trying to get the answer from the documentation but I can't seem to figure it out. Any help would be appreciated.
Since your json is like this [ {....} , [{....}] ], You can only deserialize it to an object array(Where first item is an object and second, another array).
This simplest way I think to convert it to a c# object is:
var jArr = JArray.Parse(jsonstr);
var pageInfo = jArr[0].ToObject<PagingInfo>();
var countryInfos = jArr[1].ToObject<List<CountryInfo>>();
Class definitions would be:
public class PagingInfo
{
public int page { get; set; }
public int pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int total { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class AdminRegion
{
public string id { get; set; }
public string value { get; set; }
}
public class IncomeLevel
{
public string id { get; set; }
public string value { get; set; }
}
public class LendingType
{
public string id { get; set; }
public string value { get; set; }
}
public class CountryInfo
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public AdminRegion adminregion { get; set; }
public IncomeLevel incomeLevel { get; set; }
public LendingType lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
PS: You can change the property names' first char to Uppercase if you want. I used http://json2csharp.com/ to automatically generate those classes.

Unable to deserialize a json object

I'm using JavaScriptSerializer and when I try to deserialize a JSON object as
Json.Deserialize<List<HeyWatchVideo>>(Request("video"));
I get following Exception:
MissingMethodException: No parameterless constructor defined for type of 'System.String'.
I tried matching my .NET classes, and the types of their properties just as close to my json object, but still getting above exception
My JSON object:
[{
"url": "http://media.heywatch.com.s3.amazonaws.com/14/14/a0f356a48381092e6e2a34021ce86b19/11002247",
"specs": {
"size": 3808,
"video": {
"fps": 11.63,
"height": 360,
"length": 61,
"width": 640,
"aspect": 1.78,
"codec": "mpeg4",
"container": "mov",
"rotation": 0,
"bitrate": 507,
"pix_format": "yuv420p",
"stream": 0.1
},
"thumb": "http://media.heywatch.com.s3.amazonaws.com/14/14/ad59fa501d1b9e826552dfc010cf1c98/11002247.jpg",
"audio": {
"sample_rate": 11025,
"channels": 1,
"codec": "aac",
"bitrate": 38,
"synched": true,
"stream": 0
},
"mime_type": "video/mp4"
},
"title": "elves.mp4",
"filename": "11002247",
"link": "http://heywatch.com/video/21091957.bin",
"updated_at": "2013-01-14T15:44:53+01:00",
"created_at": "2013-01-14T15:44:53+01:00",
"id": 21091957
}]
My Classes
public class HeyWatchVideo
{
public DateTime Created_At { get; set; }
public string Title { get; set; }
public Dictionary<string, string> Specs { get; set; }
public DateTime Updated_At { get; set; }
public int Id { get; set; }
public string Filename { get; set; }
public string Link { get; set; }
public string Url { get; set; }
}
public class HeyWatchVideoSpecs
{
public HeyWatchVideoSpecsAudio Audio { get; set; }
public HeyWatchVideoSpecsVideo Video { get; set; }
public string Thumb { get; set; }
public string Mime_type { get; set; }
public int Size { get; set; }
}
public class HeyWatchVideoSpecsVideo
{
public int Rotation { get; set; }
public double Aspect { get; set; }
public string Container { get; set; }
public string Codec { get; set; }
public int Length { get; set; }
public int Width { get; set; }
public int Bitrate { get; set; }
public string Pix_format { get; set; }
public double Fps { get; set; }
public double Stream { get; set; }
public int Height { get; set; }
}
public class HeyWatchVideoSpecsAudio
{
public int Channels { get; set; }
public int Sample_rate { get; set; }
public string Codec { get; set; }
public bool Synched { get; set; }
public int Bitrate { get; set; }
public int Stream { get; set; }
}
What am I doing wrong here?
My problem was solved. My .Net Classes didn't match exactly as Json object. (Both are in the question)
When they were matched, this error went away

Categories

Resources