简体   繁体   中英

Sorting a JSON Object/String on basis of keys

Straight and simple, following is a sample Json:

{
    "2014-05-27": 292,
    "2014-05-06": 323,
    "2014-05-21": 212,
    "2014-05-22": 238,
    "2014-05-23": 219
}

As clearly visible the keys are the dates and values are some counter. I need to sort this JSON on basis of dates. I am programming in java and using Jackson library if that helps.

您可以将该JSON转换为Map,然后对该Map进行排序,然后再将其转换回JSON。

According to the JSON spec :

An object is an unordered set of name/value pairs.

and

An array is an ordered collection of values.

If you wanted to do the sorting in your Java code, you could sort them by date into a list and pass the list back in your response. Jackson will do the work of converting the list into an array and preserving the order. This approach would require you to convert your key:values to objects. The objects that populate your array would look similar to this:

{
    "date": "2014-05-27",
    "value": 292
}

You will retain ordering guarantees by using an array. Using an object you have no guarantees.

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