mba mba - 3 months ago 8
JSON Question

Jackson handling of remaining fields

I wonder if this is possible.
I have a huge json file to parse and modify.
But not all fields are interresting to me : I wan't to map only fields I'm interrested in, modify them then save the whole json with all fields I didn't care left unchanged.

Then suppose I have lot of properties and only one I'm interrested in named "MyProp", I tried something like

public class MyMapper extends HashMap {
private String myProp;
public void setMyProp(String myProp) {
this.myProp = myProp;
}
public String getMyProp() {
return myProp;
}
}


But the property "MyProp" is always null (until I remove "extends HashMap").
Instead all goes in the map.

Wouldn't be useful (or is it already possible ?) to be able to mix concrete fields with maps to work with known fields without loosing unknowns ?

And it would be better to did not extend HashMap but instead having a field to hold all unknown fields like this :

public class MyMapper {
private String myProp;
private Map remaining = new HashMap();
public void setMyProp(String myProp) {
this.myProp = myProp;
}
public String getMyProp() {
return myProp;
}
@JsonRemaining
public Map getRemaining() {
return remaining;
}
}


How would you do in this case ?

Answer

Seems like @JsonAnySetter and @JsonAnyGetter annotations might help. All irrelecant proerpties get stuffed into one Map and then the map contents get dumped back to json

See how-to guide here http://vincentdevillers.blogspot.co.il/2013/08/how-to-map-unknown-json-properties-with.html