Я пытаюсь сериализовать объект Java с hashmap в строку json, используя объект сопоставления объектов Джексона.
Ниже приведено определение класса Ext
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({})
public class Ext implements Serializable {
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
private static final long serialVersionUID = -4500317258794294335L;
public Ext() {
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
// ignore toString, equals and hascode
public static class ExtBuilder {
protected Ext instance;
public ExtBuilder() {
if (this.getClass().equals(Ext.ExtBuilder.class)) {
this.instance = new Ext();
}
}
public Ext build() {
Ext result = this.instance;
this.instance = null;
return result;
}
public Ext.ExtBuilder withAdditionalProperty(String name, Object value) {
this.instance.getAdditionalProperties().put(name, value);
return this;
}
}
}
Ниже приведен пример теста -
@Test
public void testNullObjectSerialization() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setDefaultPropertyInclusion(
JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
mapper.writeValue(out, new Ext.ExtBuilder().withAdditionalProperty("unexpected", null).withAdditionalProperty("expected", true).build());
String result = new String(out.toByteArray());
Assert.assertEquals("{\"expected\":true}", result);
}
Я использовал
mapper.setDefaultPropertyInclusion(
JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));`
, используя ответ, указанный в переполнении стека вопрос .
Я ожидаю результат как {"expected":true}
, но каким-то образом ключ со значением null
включается в результат.
Как я могу исправить эту проблему?
Примечание:
- Код на github здесь .
- Я использую версию jackserion 2.9.8