Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path
Solution 1:
The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:
[A]
JObject
isn't the elementary base type of everything in JSON.net, butJToken
is. So even though you could say,object i = new int[0];
in C#, you can't say,
JObject i = JObject.Parse("[0, 0, 0]");
in JSON.net.
What you want is JArray.Parse
, which will accept the array you're passing it (denoted by the opening [
in your API response). This is what the "StartArray" in the error message is telling you.
As for what happened when you used JArray
, you're using arr
instead of obj
:
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);
Swap that, and I believe it should work.
Although I'd be tempted to deserialize arr
directly as an IEnumerable<LocationData>
, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.
Solution 2:
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());