我想知道是否有可能生成一个JSON对象与杰克逊的JsonSerializer其中的属性按值排序(而不是按键)。例如:按照自定义顺序序列化对象属性与杰克逊
{
"property2": 320,
"property1": 287,
"property4": 280,
"property3": 123,
...
}
我试图生成它创建自定义JsonSerializer这样的:
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();
}
}
但JSON产生不受属性值进行排序,杰克逊必须再次无序对象属性。有什么办法可以做到这一点?
编辑:问题不与杰克逊,但与应用程序I用于检索JSON(CocoaRestClient),这改变了在所生成的对象的属性的顺序。我的方法和@ m.aibin的方法都是正确的。 如果您有类似问题,请检查问题不在于您用于检索JSON的应用程序。
属性的顺序应该从来不管,除了*也许*易读性的目的。 –