简体   繁体   中英

Converting a Sorted Map from Java to an sorted object readable in Javascript

I have a ConcurrentSkipListMap which stores sorted data based on the timestamp since epoch. Now using Servlets I want to return this data to the browser. But, when I convert the Java map into JSON the order is lost(I know JSON doesn't maintain it). I have also tried to return a string to the user which I create while iterating the map

returnString = "{";
for (Map.Entry<Long, String> entry : mapname.entrySet()) {
    returnString += "\"" + String.valueOf(entry.getKey()) + "\":" + "\"" + entry.getValue() + "\",";
}
returnString += "}";

This String with escape sequences works untill my getValue() is a String. If it turns out to be a JSON Object, Javascript is unable to parse the entire object because the escape sequences are missing for that value.

I want to return to the browser a format which is easily readable in JavaScript and which will not require me to sort in JavaScript as my Map in Java is already sorted. Is this possible? How?

PS: I may be missing something obvious because I've had my head into this for hours.

Try the GSON library. It will help you

GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        builder.serializeNulls();
        Gson  gsonExt = builder.create();
        String serialize = gsonExt.toJson(mapname);

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