2017-07-14 27 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