2017-07-14 29 views
0

我有一个叫做LatLong的类,它存储两个stringslatitudelongitude。我有一个名为LatLongs另一类是类型的列表LatLongC#JsonConvert.DeserializeObject填充列表为空

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; } 
} 

最后我还有一个叫Locations类,它拥有JSON串称为geofence_coordinates

的JSON字符串中有两个字段,latitudelongitude,是用于将这些值存储在SQL服务器上。 JSON字符串如下所示:

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

下面是我的代码无法正常工作的地方。我有一个名为Locations的列表,名为coords。我创建了一个我打算用我的JSON坐标来填充,但此刻的JSON不能正常工作,它是被送入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(); 

我是用JsonConvert.DeserializeObject错了吗?

+0

那些JSON属性名称的开头和结尾是否真的有空格?例如。 ''纬度“'开始并以空格结束。 – dbc

+1

这是完整的json吗?包装对象在哪里呈现? –

+0

@dbc是JSON空间敏感吗? –

回答

2

你的JSON属性名称包括在开头空格和结尾:通过调整空间

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

Json.NET不会自动绑定在其名称中空格C#性能JSON性能。而且,由于C#标识符不能包含空格字符,则需要通过与一个[JsonProperty]属性标记您的属性来选择其中一种可能性从How can I parse a JSON string that would cause illegal C# identifiers?,例如:

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

样品fiddle