Gaurav Bhor
Gaurav Bhor

Reputation: 1157

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.

Upvotes: 0

Views: 264

Answers (1)

Sachin
Sachin

Reputation: 3554

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

Upvotes: 2

Related Questions