0

I have a class called LatLong which stores two strings, a latitude and longitude. I have another class called LatLongs which is a list of type LatLong

public class LatLongs
{
    public List<LatLong> latlongs { get; set; }
    public string location_name { get; set; }
}

public class LatLong
{
    public string latitude { get; set; }
    public string longitude { get; set; }
}

Finally I have another class called Locations which holds a JSON string called geofence_coordinates

The JSON string has two fields, latitude and longitude and is used to store these values on an SQL server. The JSON strings look like this:

[  
   {  
      " latitude ":"-34.95771393255739",
      " longitude ":"138.46961975097656"
   },
   {  
      " latitude ":"-34.9520861634788",
      " longitude ":"138.57330322265625"
   },
   {  
      " latitude ":"-35.00947127349485",
      " longitude ":"138.50017547607422"
   },
   {  
      " latitude ":"-35.00806525651258",
      " longitude ":"138.57467651367188"
   }
]

Below is where my code is not working properly. I have a list of type Locations called coords. I create a List<LatLongs> which I intend to populate with my JSON coordinates, but at the moment the JSON is not working properly and it is being fed null

List<Locations> coords = await locationTable.Where(u => u.fk_company_id == viewModel.UserData.fk_company_id).ToListAsync();
List<LatLongs> latLongs = coords.Select(c => new LatLongs
  {
      latlongs = JsonConvert.DeserializeObject<List<LatLong>>(c.geofence_coordinates)
  }).ToList();

Am I used JsonConvert.DeserializeObject wrong?

Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

1 Answers1

3

Your JSON property names includes spaces at the beginning and end:

" latitude ":"-35.00947127349485"  
 ^        ^  
 |        |
 here and here

Json.NET will not automatically bind JSON properties with spaces in their names to c# properties by trimming the spaces. And since c# identifiers cannot include space characters, you need to chose one of the possibilities from How can I parse a JSON string that would cause illegal C# identifiers?, for instance by marking your properties with a [JsonProperty] attribute:

public class LatLong
{
    [JsonProperty(" latitude ")]
    public string latitude { get; set; }
    [JsonProperty(" longitude ")]
    public string longitude { get; set; }
}

Sample fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340