I would like to know if it is possible to generate a JSON object with Jackson's JsonSerializer where the properties are ordered by value (not by key). For example:
{
"property2": 320,
"property1": 287,
"property4": 280,
"property3": 123,
...
}
I tried to generate it creating a custom JsonSerializer like this:
public class MySerializer extends JsonSerializer<Map<String, Long>> {
@Override
public void serialize(Map<String, Long> t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
List<Entry<String, Long>> list = new ArrayList<>(t.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Long>> () {
@Override
public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
jg.writeStartObject();
for(Entry<String, Long> entry : list) {
jg.writeNumberField(entry.getKey(), entry.getValue());
}
jg.writeEndObject();
}
}
But the JSON generated is not sorted by property value, Jackson must be disordering again the object properties. Is there any way to achieve this?
EDIT: The problem was not with Jackson, but with the application I used to retrieve the JSON (CocoaRestClient), which changes the order of the properties in the generated object. Both my approach and @m.aibin's one are correct. If you have a similar problem, please check that the problem is not the application you are using to retrieve the JSON.