【问题标题】:Trying deserialize a JSON array in C#尝试在 C# 中反序列化 JSON 数组
【发布时间】:2023-02-23 02:14:15
【问题描述】:
我在这个链接Deserialize a JSON array in C# 中有一个类似的问题
但是我无法捕获数组,所以如果有人可以看一下并告诉我做错了什么,我将不胜感激。这是我的 JSON 数组:
{
"latitude": [
{
"ts": 1677055475800,
"value": "40.480946"
}
],
"longitude": [
{
"ts": 1677055475800,
"value": "-3.37441"
}
]
}
我试过答案:
class Latitud
{
public Device latitude;
}
class Longitud
{
public Device longitude;
}
class Device
{
public string ts { get; set; }
public int value { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var mylongitude= ser.Deserialize<List<Longitud>>(jsonData);
var mylatitude = ser.Deserialize<List<Latitud>>(jsonData);
我究竟做错了什么?
【问题讨论】:
标签:
c#
arrays
json
serialization
【解决方案1】:
您的结构与源 JSON 不匹配。
您需要一个目标对象来表示整个结构。此外,您的 Device 类需要匹配存储在数组中的内部数据的结构:
//This represents your main structure
public class SomeTargetObject
{
public Device[] Latitude { get; set; }
public Device[] Longitude { get; set; }
}
//This represents the inner data
public class Device
{
public string ts { get; set;}
public string value { get; set; }
}
最后,我建议使用 Newtonsoft.Json 包中的 NewtonSoft 来反序列化它:
var json = @"{
""latitude"": [
{
""ts"": 1677055475800,
""value"": ""40.480946""
}
],
""longitude"": [
{
""ts"": 1677055475800,
""value"": ""-3.37441""
}
]
}";
var obj = JsonConvert.DeserializeObject<SomeTargetObject>(json);
JsonConvert 可以在Newtonsoft.Json 命名空间中找到。
【解决方案2】:
当您将 JSON 字符串 jsonData 反序列化为 mylatitude 和 mylongitude 变量时,您分别使用了 Deserialize<List>(jsonData) 和 Deserialize<List>(jsonData) 方法。
但是,JSON 对象中的纬度和经度属性是数组,而不是对象。因此,您应该将它们反序列化为 Coordinate 对象列表,而不是 Latitud 或 Longitud 对象列表。
你能试试这个吗
public class Location
{
public List<Coordinate> latitude { get; set; }
public List<Coordinate> longitude { get; set; }
}
public class Coordinate
{
public long ts { get; set; }
public string value { get; set; }
}
// Deserialize the JSON string into an object
string jsonString = "Your JSON code";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Location location = serializer.Deserialize<Location>(jsonString);