让RestEasy / Jackson返回用引号括起来的长片

时间:2012-04-01 15:03:27

标签: java json jackson resteasy

Javascript无法处理我的长篇,所以我希望RestEasy用引号将它们包起来将它们变成字符串。

我的DTO是:

public class DTO {
    Long id;
}

我希望将其转为{"id":"2394872352498"}

不幸的是,现在(默认情况下)它会被转移为{"id":2394872352498},这会导致问题。

我正在使用杰克逊来序列化数据。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案:

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;

public class LongToStringSerializer extends SerializerBase<Long>{


    public LongToStringSerializer(Class<?> t, boolean dummy) {
        super(t, dummy);
    }

    @Override
    public void serialize(Long arg0, JsonGenerator arg1, SerializerProvider arg2)
            throws IOException, JsonProcessingException {
        arg1.writeString(arg0 == null ? null : arg0.toString());
    }

}

然后,需要注册此序列化程序:

SimpleModule simpleModule = new SimpleModule("MyModule", new Version(0, 0, 0, null));
simpleModule.addSerializer(new LongToStringSerializer(Long.class, true));
objectMapper.registerModule(simpleModule);