Pergunta

For deserializing json with unknown field into an object there's @JsonAnySetter.

But what if I read such json into my object, modify some known fields and write it back to json? The unknown properties will be lost.

How do I handle such cases? Is it possible to map an object or do I have to read the data into a JsonNode or Map?

Foi útil?

Solução

Unmarshalling into a custom java class has its advantages and disadvantages. It's gives you nice static typing, but it's well, static. The javadoc for @JsonAnySetter suggests that it's similar to JAXB's @XmlAnyElement, but unlike @XmlAnyElement, the data objects don't contain naming information, so it's a one-way street.

if you need to handle dynamic JSON streams, then you need to bite the bullet and use Map or JsonNode.

Outras dicas

There's this RFE for Jackson: http://jira.codehaus.org/browse/JACKSON-292 to add such a feature. Makes total sense when you think about it.

It is now possible to use @JsonAnyGetter to provide a method which allows serialization of dynamic properties:

@JsonAnyGetter
public Map<String, String> getDynamicProperties() {
    return dynamicProperties; // a field like this exists
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top