我正在使用Jackson来反序列化Product
接口的许多不同实现。这些产品实现具有不同的字段,但是都具有InsuredAmount
字段。该InsuredAmount
类具有一个值字段和一个IAType
字段。 IAType
是一个标记接口,具有不同的枚举作为实现。
现在是问题所在:IAType
接口的枚举实现对应于Product
接口的特定实现。如何进行通用实现并告诉Jackson寻找IAType的正确实现?我是否应该在Product和IAType接口上使用通用参数来标识产品实现?是否应该在用于标识产品实现的类上使用Productable
功能接口?我如何告诉 jackson 使用该实现?
我希望下面的代码可以澄清问题,我选择在此处实现Productable
接口,但是也欢迎使用更好的结构来解决此问题。
@JsonPropertyOrder({"type", "someInfo"})
public class InsuredAmount implements Productable, Serializable {
private static final long serialVersionUID = 1L;
private IAType type;
private String someInfo;
public InsuredAmount() {
}
public InsuredAmount(IAType typeA, String someInfo) {
this.type = typeA;
this.someInfo = someInfo;
}
/* This should be on the product level, but if I can solve this problem,
the next level will just be more of the same.
*/
@JsonIgnore
@Override
public Product getProduct() {
return Product.PROD_A;
}
// Getters, setters, equals, etc. omitted.
}
-
public interface Productable {
public Product getProduct();
}
-
public enum Product {
PROD_A, PROD_B;
}
-
@JsonDeserialize(using = IATypeDeserializer.class)
public interface IAType extends Productable {
}
-
public enum IATypeA implements IAType {
FOO, BAR;
@Override
public Product getProduct() {
return Product.PROD_A;
}
}
-
public class IATypeDeserializer extends StdDeserializer<IAType> {
private static final long serialVersionUID = 1L;
public IATypeDeserializer() {
this(null);
}
public IATypeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public IAType deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
JsonNode node = parser.getCodec().readTree(parser);
/* How to find out that the class calling the deserialization is InsuredAmountA, which
has getProduct() method that returns PROD_A, and matches the IATypeA that also returns
PROD_A, so I know to deserialize IATypeA, instead of other implementations of the IAType
interface?
*/
return IATypeA.valueOf(node.asText());
}
}
-
public class InsuredAmountTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void test01() throws IOException {
InsuredAmount iaA = new InsuredAmount(IATypeA.FOO, "test it");
String json = mapper.writeValueAsString(iaA);
assertThat(json, is("{\"type\":\"FOO\",\"someInfo\":\"test it\"}"));
InsuredAmount iaA2 = mapper.readValue(json, InsuredAmount.class);
IAType type = iaA2.getType();
assertThat(type, is(IATypeA.FOO));
assertThat(type.getProduct(), is(Product.PROD_A));
assertThat(iaA, is(iaA2));
}
@Test
public void test02() throws IOException {
InsuredAmount iaA = new InsuredAmount(IATypeA.BAR, "test it");
String json = mapper.writeValueAsString(iaA);
assertThat(json, is("{\"type\":\"BAR\",\"someInfo\":\"test it\"}"));
InsuredAmount iaA2 = mapper.readValue(json, InsuredAmount.class);
assertThat(iaA, is(iaA2));
}
}
最佳答案
Jackson用最少的麻烦处理了枚举的序列化,因此您要做的就是用IAType
注释@JsonTypeInfo
字段:
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS)
private IAType type;
然后进行测试:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new InsuredAmount(IATypeA.FOO, "info"));
System.out.println(json);
InsuredAmount ia = mapper.readValue(json, InsuredAmount.class);
System.out.println("Type is: " + ia.getType());
}
结果输出:
{"type":[".IATypeA","FOO"],"someInfo":"info"}
Type is: FOO
为了获得更紧凑的表示,您将必须使用自定义序列化。假设枚举名称空间中没有重叠,则可以将类型字段序列化为枚举名称。
解串器将需要知道哪些类型可用于构造,可以通过类路径发现,也可以像下面的示例中那样简单地对引用进行硬编码:
public class IATest {
public static class IATypeSerializer extends JsonSerializer<IAType> {
@Override
public void serialize(IAType value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(((Enum) value).name());
}
}
public static class IATypeDeserializer extends JsonDeserializer<IAType> {
@Override
public IAType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.readValueAs(String.class);
try {
return IATypeA.valueOf(value);
} catch (IllegalArgumentException e) {
// fall through
}
try {
return IATypeB.valueOf(value);
} catch (IllegalArgumentException e) {
// fall through
}
throw new JsonMappingException(p, "Unknown type '" + value + "'");
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Register a module to handle serialization of IAType implementations
SimpleModule module = new SimpleModule();
module.addSerializer(IAType.class, new IATypeSerializer());
module.addDeserializer(IAType.class, new IATypeDeserializer());
mapper.registerModule(module);
// Test
String json = mapper.writeValueAsString(new InsuredAmount(IATypeA.FOO, "info"));
System.out.println(json);
InsuredAmount ia = mapper.readValue(json, InsuredAmount.class);
System.out.println("Type is: " + ia.getType());
}
}
哪个输出:
{"type":"FOO","someInfo":"info"}
Type is: FOO