使用Jackson对已排序的键进行序列化的JSON [英] Serialized JSON with sorted keys, using Jackson

查看:554
本文介绍了使用Jackson对已排序的键进行序列化的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我无法让杰克逊输出一个符合JSON(de)序列的自定义JSON用按照简单的'自然'字母顺序排序的键的漂亮打印的JSON。
我试过这个(以及许多变体):

  mymap = [...] //一些常规地图
DEF映射器=新ObjectMapper()
mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,真)
DEF jsonstring = mapper.defaultPrettyPrintingWriter()。writeValueAsString(MyMap中)

但是Jackson固执地生成一个JSON,其中的按键似乎是随机排列的。
我试着用TreeMap改变'mymap'的类型,在这种情况下,所有键都按预期正确排序。



我想知道如果有一种方法可以将排序而不是将上面的'mymap'更改为TreeMap(以及递归地映射其所有映射值...)的方法。



SORT_PROPERTIES_ALPHABETICALLY似乎打算做到这一点,但不是出于某种原因这样做。
你知道这是为什么吗?我上面做错了什么?



我已经尝试了Jackson 1.8.3,1.8.8和1.9.5,结果相同(随机密钥)。 p>

解决方案

The SORT_PROPERTIES_ALPHABETICALLY 明确表示:


定义用于POJO字段的默认属性序列化顺序的功能(注意:不适用适用于Map序列化!)


所以我想你需要改变你的输入Map(如你所说)


I'm trying to replace a custom JSON (de)serialization in a groovy/grails project with Jackson.

I'm having trouble getting Jackson to output a pretty-printed JSON with keys sorted in a simple 'natural' alphabetic order. I've tried this (and many variations):

mymap = [ ... ] // Some groovy map
def mapper = new ObjectMapper()
mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
def jsonstring = mapper.defaultPrettyPrintingWriter().writeValueAsString(mymap)

But Jackson stubbornly generates a JSON where the keys seem to be in a random order. I've tried changing the type of 'mymap' with a TreeMap, and in that case all keys are properly sorted as expected.

I'm wondering if there is a way to get the keys sorted without changing 'mymap' above to a TreeMap (and recursively all of its map values...).

SORT_PROPERTIES_ALPHABETICALLY seems to be intended to do precisely that, but it's not doing it for some reason. Would you know why that is? Anything I'm doing wrong above?

I've tried with Jackson 1.8.3, 1.8.8 and 1.9.5, same result (random keys).

解决方案

The documentation for SORT_PROPERTIES_ALPHABETICALLY explicitly says:

Feature that defines default property serialization order used for POJO fields (note: does not apply to Map serialization!)

So I guess you will need to change your input Map (as you say)

这篇关于使用Jackson对已排序的键进行序列化的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆