简体   繁体   English

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

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

I'm working with dates and times but my json file puts the newest instance first.我正在处理日期和时间,但我的 json 文件将最新的实例放在首位。 I'd like to be able to iterate through the array in linear order([0,1,2,3]) from oldest to newest entrie.我希望能够以线性顺序([0,1,2,3])从最旧到最新的条目遍历数组。 Im using Newtonsoft to deserialize the json.我使用 Newtonsoft 反序列化 json。 How do I go about reversing the order of this?我该如何去颠倒这个顺序?

Here is my object这是我的对象

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

Here is a small sample of the json这是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
  } ]
}

Here are my classes这是我的课

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

You can use LINQ to sort Location objects in whatever order you want:您可以使用 LINQ 按您想要的任何顺序对Location对象进行排序:

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

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

NOTE: Newtonsoft json deserializer do not change order of objects.注意:Newtonsoft json 反序列化器不会改变对象的顺序。

This is what worked for me.这对我有用。 Thanks every body for the help!感谢每一位身体的帮助!

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

Array.Reverse(jObj.locations);

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

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