简体   繁体   中英

How to extract value of a latest timestamp from a json using Gson?

I have a JSON string like this -

{"error_1395991841806": "ErrorA", "error_1395991131941": "ErrorB", "error_1395991534713": "ErrorC", "error_1395991772241": "ErrorD"}

In the above JSON string, I have all the keys in this format error_timestampInMilliseconds .

Now I want to sort all the keys in the descending order of the timestamp and then extract the value of that latest error_timestamp key . Meaning whatever timestamp is the latest as compared to current timestamp , I will use that key to extract the value of it. Is this possible to do?

I am using Gson for JSON. Below is my code -

String data = new String(event.getData().getData(), Charset.forName("UTF-8"));

// here this data is my json string
System.out.println(data);

JsonObject jsonObject = gson.fromJson(data, JsonObject.class); // parse

So suppose if this is the latest timestamp error_1395991841806 as compared to current timestamp, I will print out ErrorA as its value.

Your JSON represents a Map<String, String> , and you want to get the highest Key , so you may try deserializing your JSON into a TreeMap , which is exactly a Map sorted by Key ...

Type yourMapType = new TypeToken<TreeMap<String, String>>() {}.getType();
TreeMap<String, String> yourMap = gson.fromJson(yourJsonString, yourMapType);

String highestKey = yourMap.lastKey();
String lastError = yourMap.get(highestKey);

Now lastError should contain "ErrorA" .

Note that I didn't try this, but I guess it should work...


EDIT : If for some reason you cannot deserialize directly into a TreeMap (although I guess you should be able to do it), try deserializing into a generic Map , and then construct a TreeMap from it, like this:

Type yourMapType = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> yourGenericMap = gson.fromJson(yourJsonString, yourMapType);
TreeMap<String, String> yourMap = new TreeMap<>(yourGenericMap);
// ...

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