如何在Jackson中使用自定义Serializer? [英] How do I use a custom Serializer with Jackson?
问题描述
我想要使用Jackson将两个Java类序列化为JSON:
I have two Java classes that I want to serialize to JSON using Jackson:
public class User {
public final int id;
public final String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Item {
public final int id;
public final String itemNr;
public final User createdBy;
public Item(int id, String itemNr, User createdBy) {
this.id = id;
this.itemNr = itemNr;
this.createdBy = createdBy;
}
}
我想将一个Item序列化为这个JSON:
I want to serialize an Item to this JSON:
{"id":7, "itemNr":"TEST", "createdBy":3}
用户序列化为仅包含 id
。我还可以将所有用户对象邮件化为JSON,如:
with User serialized to only include the id
. I will also be able to serilize all user objects to JSON like:
{"id":3, "name": "Jonas", "email": "jonas@example.com"}
所以我想我需要为项目
编写自定义序列化程序并尝试使用:
So I guess that I need to write a custom serializer for Item
and tried with this:
public class ItemSerializer extends JsonSerializer<Item> {
@Override
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeNumberField("itemNr", value.itemNr);
jgen.writeNumberField("createdBy", value.user.id);
jgen.writeEndObject();
}
}
我使用此代码序列化JSON来自 Jackson How-to:Custom Serializers :
I serialize the JSON with this code from Jackson How-to: Custom Serializers:
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule",
new Version(1,0,0,null));
simpleModule.addSerializer(new ItemSerializer());
mapper.registerModule(simpleModule);
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, myItem);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但我收到此错误:
Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() (use alternative registration method?)
at org.codehaus.jackson.map.module.SimpleSerializers.addSerializer(SimpleSerializers.java:62)
at org.codehaus.jackson.map.module.SimpleModule.addSerializer(SimpleModule.java:54)
at com.example.JsonTest.main(JsonTest.java:54)
如何我可以在杰克逊上使用自定义串行器吗?
这就是我用Gson做的方法:
This is how I would do it with Gson:
public class UserAdapter implements JsonSerializer<User> {
@Override
public JsonElement serialize(User src, java.lang.reflect.Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.id);
}
}
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(User.class, new UserAdapter());
Gson gson = builder.create();
String json = gson.toJson(myItem);
System.out.println("JSON: "+json);
但我现在需要和杰克逊一起做,因为Gson不支持接口。 / p>
But I need to do it with Jackson now, since Gson doesn't have support for interfaces.
推荐答案
如上所述,@ JsonValue是一个好方法。但是如果你不介意自定义序列化程序,则不需要为Item编写一个,而是为User写一个 - 如果是这样的话,它就像这样简单:
As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeNumber(id);
}
另一种可能性是实现 JsonSerializable
,在这种情况下不需要注册。
Yet another possibility is to implement JsonSerializable
, in which case no registration is needed.
关于错误;这很奇怪 - 你可能想要升级到更高版本。但扩展 org.codehaus.jackson.map.ser.SerializerBase
也更安全,因为它将具有非必要方法的标准实现(即除了实际的序列化调用之外的所有内容) 。
As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase
as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).
这篇关于如何在Jackson中使用自定义Serializer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!