简体   繁体   中英

C# Not able to read json Response from API Call

I call a Weather API - which returns Json response. My C# Code-

           Uri uri1 = new Uri(APIUrl);
           WebRequest webRequest1 = WebRequest.Create(uri1);
           WebResponse response1 = webRequest1.GetResponse();
           StreamReader streamReader1 = new StreamReader(response1.GetResponseStream());
           String responseData1 = streamReader1.ReadToEnd().ToString();
           dynamic data1 = JObject.Parse(responseData1 )

I get Exception while calling Parse as below- An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll

Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

My Analysis- responseData1 has json strings as-

responseData1="[{\"locationName\":\"Bangalore\",\"subLocationName\":null,\"gid\":\"43295\",\"subStateID\":null,\"subStateName\":null,\"stateID\":\"II\",\"stateName\":\"Indien\",\"latitude\":12.9667,\"longitude\":77.5833,\"altitude\":900,\"zip\":null}\n, {\"match\":\"yes\"}]"

If i check this json in http://jsonlint.com/ - It says valid json.

If i hit my APIUrl directly in browser- repose in browser is as below-

[{"locationName":"Bangalore","subLocationName":null,"gid":"43295","subStateID":null,"subStateName":null,"stateID":"II","stateName":"Indien","latitude":12.9667,"longitude":77.5833,"altitude":900,"zip":null}, {"match":"yes"}]

My aim is to read the value of property "gid" from the above json. Can someone help me here? Thanks!

You're using the JObject class, when you should be using the JArray class, because the JSON you're attempting to parse is an array - not an object:

http://www.newtonsoft.com/json/help/html/ParseJsonArray.htm

It would be better to create a model for this. Then you can simply tell Newtonsoft to deserialize the JSON string instead of using a dynamic type.

First, you would need to create a model like this:

public class WeatherData
{
    public string locationName { get; set; }
    public string subLocationName { get; set; }
    public string gid { get; set; }
    public int subStateID { get; set; }
    public string subStateName { get; set; }
    public string stateID { get; set; }
    public string stateName { get; set; }
    public double latitude { get; set; }
    public double longitude { get; set; }
    public int altitude { get; set; }
    public string zip { get; set; }
    public string match { get; set; }
}

Then deserialize the return JSON as follows:

var data1 = JsonConvert.DeserializeObject<WeatherData>(responseData1);

Or for an array:

var data1 = JsonConvert.DeserializeObject<List<WeatherData>>(responseData1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM