How do I marshall nested key,value pairs into JSON with Camel and Jackson library?

眉间皱痕 提交于 2019-12-03 04:37:37

Your structure is a more than a map. It's two maps that are serialised differently. One way to represent this is:

public class Whatever{
  Map<String,String> keyvalues;
  Map<String,String> visibility;
}

What you'll end up with is this, which although represents the data is far from ideal:

{
 "keyvalues" : { "key1": "5", "key2": "10", "key3": "17"},
 "visibility" : { "key1": "a&b&!c", "key2": "a&b", "_default": "a" }
}

To get what you want, use @JsonAnyGetter. Something like this (it could be made much easier to use):

public class Whatever{
    Map<String,String> keyvalues = new TreeMap<String,String>();
    @JsonProperty
    Map<String,String> visibility = new TreeMap<String,String>();

    @JsonAnyGetter
    public Map<String, String> getKeyvalues() {
        return keyvalues;
    }
}

which produces:

           {"visibility":{"key1":"a&b&!c","key2":"a&b"},"key1":"5","key2":"10"}

I've been battling this today and your question inspired me to make it bloody work :D The annotations are here: https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations

See JUnit test here: https://gist.github.com/TomDemeranville/7009250

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!