Jackson fasterxml和codehaus, 和排序-order by

来源:互联网 发布:软件成功案例 编辑:程序博客网 时间:2024/05/16 10:54

fasterxml和codehaus的区别

是jackson的两个分支、也是两个版本的不同包名.
- 1.x版本的包名是codehaus, 1.x版本现在只提供bug-fix;
- 2.0开始改用新的包名fasterxml, 2.x版本还在不断开发和发布中;

json的排序和equal

业务开发中遇到json的处理. 但是拿到的json的key的顺序是不稳定的.

两个思路:
1.比较两个json是否相同;
2.递归遍历序列化排序, 转换为string.

比较两个json是否相同

可以使用jackson的ObjectNode.equals()

public boolean equals(Object o){    if (o == this) return true;    if (o == null) return false;    if (o.getClass() != getClass()) {        return false;    }    ObjectNode other = (ObjectNode) o;    if (other.size() != size()) {        return false;    }    if (_children != null) {        for (Map.Entry<String, JsonNode> en : _children.entrySet()) {            String key = en.getKey();            JsonNode value = en.getValue();            JsonNode otherValue = other.get(key);            if (otherValue == null || !otherValue.equals(value)) {                return false;            }        }    }    return true;}

order by 序列化json

private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();static {    SORTED_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);}private String convertNode(final JsonNode node) throws JsonProcessingException {    final Object obj = SORTED_MAPPER.treeToValue(node, Object.class);    final String json = SORTED_MAPPER.writeValueAsString(obj);    return json;}
0 0
原创粉丝点击