-2

I have data in the following format. I want to convert this data to objects.

 Result = {
 "Location": [
 "bangalore",
  1,
 "chennai",
  1,
 "mumbai",
  1,
 "delhi",
  0,
 "Agra",
  0
 ]
 }

In my Location.cs i have the following fields. i want to assign the data to this fields. How can i achieve this

public string loc { get; set; }
public int count { get; set; }

I tried with

 Location = Result.ToObject<List<Location>>();

but not working getting the following error

{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[Location]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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) 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.\r\nPath 'Location'."}

Steve B
  • 36,818
  • 21
  • 101
  • 174
Superprogrammer
  • 109
  • 1
  • 5

3 Answers3

1

Take a look at the native json deserializaton that is part of .NET

MSDN - How to: Serialize and Deserialize JSON Data

Nitram
  • 6,486
  • 2
  • 21
  • 32
0

The problem is this: Result is a JSON object, not a JSON array, therefore you can't convert it to a List<Location>.

You would need a class that contains a list of locations and convert to that class:

public class LocationsContainer
{
    public List<Location> Location { get; set; }
}

Result.ToObject<LocationsContainer>();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

Try with Json.NET library.

List<Location> locations = JsonConvert.DeserializeObject<List<Location>>(result);
zholinho
  • 460
  • 1
  • 5
  • 17