首页 > 解决方案 > Newtonsoft.Json.JsonSerializationException: '无法反序列化当前 JSON 对象

问题描述

错误 :

Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[MFBDCP.HotelList+geolocation]' 因为该类型需要正确反序列化的 JSON 数组(例如 [1,2,3])。

我的代码:

HotelResponse myDetails = JsonConvert.DeserializeObject<HotelResponse>(final);

父类:

public class HotelResponse
{
   public List<hotels> hotels { get; set; } = new List<hotels>();
   public DateTime checkin { get; set; }
}

儿童班:

public class hotels
{
   public string hotel_code { get; set; }
   public List<geolocation> geolocation { get; set; }
}

子子类:

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

请让我知道如何定义嵌套列表

标签: c#json-deserialization

解决方案


您可能在输入字符串 final 中有错误。错误消息表明其中一个数组(列表)的格式不正确。由于您有嵌套列表,因此可能是内部数组或外部数组的格式不正确。

我要做的是,以编程方式创建一个实际的 HotelResponse 对象,它包含与 final 相同的属性值。然后,使用 JsonConvert.SerializeObject() 查看 Json 应该是什么样子。通过将 JsonConvert.SerializeObject 的结果与 final 进行比较,您应该能够找出问题所在。


推荐阅读