2017-07-10 27 views
0

我有2个类,LatLong其中包含2个字符串,latitude and longitudeLatLongs其中包含list<LatLong>C#JSON不能正确使用Newtownsoft.Json解析

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

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

我想使用Newtownsoft.JsonJsonConvert.DeserializeObject功能到我的JSON字符串转换成LatLong列表。这里是我的JSON

[ 
    { 
     "latitude":"-34.978113", 
     "longitude":"138.516192" 
    }, 
    { 
     "latitude":"-34.978104", 
     "longitude":"138.516648" 
    }, 
    { 
     "latitude":"-34.978384", 
     "longitude":"138.516660" 
    }, 
    { 
     "latitude":"-34.978398", 
     "longitude":"138.516225" 
    } 
] 

这JSON是有效的,并已检查here

当我尝试使用JsonConvert.DeserializeObject我得到一个异常

无法反序列化当前的JSON阵列(例如[ 1,2,3])转换为 'SafeAgSystems.Models.LatLongs'类型,因为该类型需要JSON 对象(例如{“name”:“value”})才能正确反序列化。

这里是我使用的尝试将JSON转换成LatLong

List<Locations> coords = await locationTable.Where(u => u.fk_company_id == viewModel.UserData.fk_company_id).ToListAsync(); 
List<LatLongs> latLongs = new List<LatLongs>(); 
for (int i = 0; i < coords.Count(); i++) 
{ 
    LatLongs latlongs = new LatLongs(); 
    latlongs = JsonConvert.DeserializeObject<LatLongs>(coords[i].geofence_coordinates); 
    latLongs.Add(latlongs); 

} 

我已经检查的另一件事列表中的代码是我List<Locations> coords被填充,这是绝对是。我完全卡住了,我错过了什么?

回答

2

您试图反序列化为LatLongs,其中一个属性名称为latlongs,其类型为List<LatLong>。另一方面,你用包含List<LatLong>(没有latlongs属性)的字符串喂它。

您需要更改您的代码

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(); 
+1

感谢伊万,你是一个精灵! –

0

我认为你没有实例化列表属性。试试下面的代码

List<Locations> coords = await locationTable.Where(u => u.fk_company_id == viewModel.UserData.fk_company_id).ToListAsync(); 
List<LatLongs> latLongs = new List<LatLongs>(); 
for (int i = 0; i < coords.Count(); i++) 
{ 
    LatLongs latlongs = new LatLongs(); 
    latlongs.latlongs = new List<LatLong>(); //Property instantiation 
    latlongs.latlongs= JsonConvert.DeserializeObject<LatLongs>(coords[i].geofence_coordinates).ToList(); 
    latLongs.Add(latlongs); 

} 

你也可以在类中有构造函数来实例化它。

+0

谢谢优素福我给一个尝试,看我怎么去 –