我想知道是否可以用 Jackson 的 JsonSerializer 生成一个 JSON 对象其中属性按值排序(而不是按键)。例如:
{
"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 不是按属性值排序的,Jackson 一定是又把对象属性打乱了。有什么办法可以实现吗?
编辑: 问题不在于 Jackson,而在于我用来检索 JSON (CocoaRestClient) 的应用程序,它改变了生成对象中属性的顺序。我的方法和@m.aibin 的方法都是正确的。 如果您遇到类似问题,请检查问题是否出在您用于检索 JSON 的应用程序上。
最佳答案
您可以对 map 进行排序,然后将其序列化。使用 Jackson 2.3.1,您可以序列化 SortedMap,例如 LinkedHashMap,顺序将得到遵守。
链接如何对 HashMap 进行排序的示例如下:Sorting HashMap by values
关于java - 使用 Jackson 以自定义顺序序列化对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048681/