How to serialize an object with jakcson and add dynamic field to it
我必须参加以下课程:
1 2 3 4 5 6 7 8 9 10 11 | public class CustomClass { @JsonProperty("Value") private boolean value; @JsonProperty("OtherObjects") private List<OtherObjects> objects; @JsonProperty("Num") private int num; @JsonIgnore public String dynamicParameterKey; } |
反序列化时,我得到此对象,作为嵌套对象的一部分,每个嵌套对象都有反序列化和序列化的规则。
但是在序列化时,我需要此对象添加另一个字段,该字段以" dynamicParamterKey "作为其键,并以" value "作为其值
由于键是动态的,因此我无法在编译时添加字段。
所以我需要做的是按常规方式序列化对象并添加此自定义字段。
该类是一整套类的一部分,因此我需要尽可能地对其进行封装(不使用自定义反序列化器并将其添加到ObjectMapper),并且我可以使用treeMap或其他东西,因为它是一个发送给我的较大json的一部分。
我该如何实现?
经过调查并从许多来源收集了零件,我想出了以下解决方案:
您需要使您的类实现JsonSerializable,以便可以进行自定义序列化。
现在,因为您要使用默认序列化并仅添加默认序列化,因此需要使用BeanSerializerFactory来执行此操作。
所以它看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class CustomClass implements JsonSerializable { @JsonProperty("Value") private boolean value; @JsonProperty("OtherObjects") private List<OtherObjects> objects; @JsonProperty("Num") private int num; @JsonIgnore public String dynamicParameterKey; //We do this so Jackson will know how to serialize with dynamic parameter key @Override public void serialize(JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); //use default serializer JavaType javaType = provider.constructType(RegulationAnswer.class); BeanDescription beanDesc = provider.getConfig().introspect(javaType); JsonSerializer<Object> serializer = BeanSerializerFactory.instance.findBeanSerializer(provider, javaType, beanDesc); serializer.unwrappingSerializer(null).serialize(this, gen, provider); //add custom fields gen.writeBooleanField(dynamicParameterKey, isChecked()); gen.writeEndObject(); } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { serialize(gen, serializers); } } |