【发布时间】:2016-12-22 15:11:33
【问题描述】:
我正在使用 Jackson 序列化关于其中数百个其他对象的大型对象。这带来了性能问题。
大部分自定义序列化类与“JSONSerializer”类中的“AmountAsStringSerializer”相同,全部定义为静态。
我的(T 对象)中有一个对象数组,增加了处理时间。当它有 40 个元素时,持续 25 秒,超过 70 个元素,持续近 3 分钟,并继续这样。
我知道其他序列化 3rd 方 API,但系统非常繁重,因此我们暂时无法迁移到它们。我需要杰克逊的解决方案。 有谁知道如何改进这个 Jackson 序列化过程?
在那里你可以看到我的实现:
public class JSONSerializer {
private static ObjectMapper mapper = null;
static {
mapper = new ObjectMapper();
addModule(mapper);
configure(mapper);
}
public static <T> String serializeObject(T object) {
String str= null;
try {
str = writer.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return str;
}
private static void addModule(ObjectMapper om) {
SimpleModule module = new SimpleModule("ModuleName", new Version(1, 0, 0, null, "", ""));
module.addSerializer(new AmountAsStringSerializer());
//and nearly one hundred serializer module
//.
//.
}
private static void configure(ObjectMapper om) {
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
}
static class AmountAsStringSerializer extends StdSerializer<Amount> {
protected AmountAsStringSerializer() {
super(Amount.class);
}
@Override
public void serialize(Amount value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
jsonGenerator.writeStartObject();
if (value != null && value.getContent() != null) {
jsonGenerator.writeStringField("content", value.getContent().toString());
}
else {
jsonGenerator.writeNull();
}
jsonGenerator.writeEndObject();
}
}
}
【问题讨论】:
标签: java json serialization jackson