简体   繁体   中英

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. I'd like to be able to iterate through the array in linear order([0,1,2,3]) from oldest to newest entrie. Im using Newtonsoft to deserialize the 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

{
  "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:

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.

This is what worked for me. Thanks every body for the help!

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

Array.Reverse(jObj.locations);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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