繁体   English   中英

反转反序列化的 json.net 对象的顺序

[英]Reversing the order of a deserialized json.net object

我正在处理日期和时间,但我的 json 文件将最新的实例放在首位。 我希望能够以线性顺序([0,1,2,3])从最旧到最新的条目遍历数组。 我使用 Newtonsoft 反序列化 json。 我该如何去颠倒这个顺序?

这是我的对象

    // Converts json file to a serialized array of locations 
    JsonObjector jObj = JsonConvert.DeserializeObject<JsonObjector>(jsonFile);

这是json的一个小示例

{
  "locations" : [ {
    "timestampMs" : "1482139582626",
    "latitudeE7" : 611636226,
    "longitudeE7" : -1498703826,
    "accuracy" : 23
  }, {
    "timestampMs" : "1482139560770",
    "latitudeE7" : 611636226,
    "longitudeE7" : -1498703826,
    "accuracy" : 23
  }, {
    "timestampMs" : "1482139441012",
    "latitudeE7" : 611636226,
    "longitudeE7" : -1498703826,
    "accuracy" : 23
  }, {
    "timestampMs" : "1482139355650",
    "latitudeE7" : 611636226,
    "longitudeE7" : -1498703826,
    "accuracy" : 23
  } ]
}

这是我的课

public class JsonObjector
{
    public Location[] locations { get; set; }
}
public class Location
{
    public string timestampMs { get; set; }
    public int latitudeE7 { get; set; }
    public int longitudeE7 { get; set; }
    public int accuracy { get; set; }
}

您可以使用 LINQ 按您想要的任何顺序对Location对象进行排序:

JsonObjector jObj = JsonConvert.DeserializeObject<JsonObjector>(jsonFile);

foreach(var location in jObj.locations.OrderBy(l => l.timestampsMs))
   // use location

注意:Newtonsoft json 反序列化器不会改变对象的顺序。

这对我有用。 感谢每一位身体的帮助!

JsonObjector jObj = JsonConvert.DeserializeObject<JsonObjector>(jsonFile);

Array.Reverse(jObj.locations);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM