【问题标题】:C# JSON not parsing correctly using Newtownsoft.JsonC# JSON 未使用 Newtonsoft.Json 正确解析
【发布时间】:2017-07-10 23:37:56
【问题描述】:

我有 2 个类,LatLong 包含 2 个字符串,latitude and longitudeLatLongs 包含 list<LatLong>

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

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

我正在尝试使用 Newtownsoft.Json JsonConvert.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&lt;Locations&gt; coords 正在被填充,这绝对是。我完全被卡住了,我错过了什么?

【问题讨论】:

    标签: c# json xamarin deserialization


    【解决方案1】:

    您正试图反序列化为 LatLongs,它有一个名为 latlongs 的属性,类型为 List&lt;LatLong&gt;。另一方面,您正在使用包含List&lt;LatLong&gt;(没有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();
    

    【讨论】:

    • 谢谢伊万,你是个巫师!
    【解决方案2】:

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

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

    您还可以在类中使用构造函数来实例化它。

    【讨论】:

    • 谢谢优素福,我会试试看我怎么走
    猜你喜欢
    • 2012-12-17
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多