writeValueAsString(object)时添加自定义属性

时间:2017-09-01 07:54:03

标签: java jackson

我有一个id(Long),js无法处理它。所以当我返回id时,我想返回另一个属性id_str。

就像:

{"id":43777753494847488, "id_str":"43777753494847488"}

我正在使用fastxml jackson writeValueAsString(object)方法。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

无法重写JsonSerializer。也许这对我来说很难。所以我修改了json字符串。这是代码:

public static String expandUserIDStr(String json) {
    String key = "user_id";
    String expandKey = "user_id_str";

    String r = "\"" + key + "\":(\\d+)[,]{0,1}";
    Pattern patter = Pattern.compile(r);
    Matcher matcher = patter.matcher(json);

    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        String expandContent = "\"" + expandKey + "\":\"" + matcher.group(1) +"\"," + matcher.group(0);
        System.out.println(expandContent);
        matcher.appendReplacement(buffer, expandContent);
    }
    matcher.appendTail(buffer);

    return buffer.toString(); 
}