Search code examples
c#jsonjson.netdeserializationjsonserializer

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!


Solution

  • 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