如何在 Jackson 中使用自定义序列化程序? [英] How do I use a custom Serializer with Jackson?
问题描述
我有两个 Java 类要使用 Jackson 序列化为 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"}
所以我想我需要为 Item
编写一个自定义序列化程序并尝试这样做:
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();
}
}
我使用来自 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)
如何在 Jackson 中使用自定义序列化程序?
这就是我对 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);
但我现在需要和 Jackson 一起做,因为 Gson 不支持接口.
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 中使用自定义序列化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!