Java – Jackson captures unrecognized fields in the map
•
Java
I use Jackson in Java rest API to handle request parameters
My class:
public class ZoneModifBeanParam extends ModifBeanParam<Zone> {
@FormParam("type")
private String type;
@FormParam("geometry")
private Geometry geometry;
@FormParam("name")
private String name;
...
My API interface:
@POST
@Consumes("application/json")
@Produces("application/json; subtype=geojson")
@ApiOperation(value = "Create a zone",notes = "To create a zone")
public Response createZone(ZoneModifBeanParam zoneParam) {
...
This works, but I need to receive other parameters that my bean does not specify in the map Example:
{
"geometry": {...},"name": "A circle name","type": "4","hello": true
}
By receiving this, I need to store the couple ("hello", real) in a map (named unrecognized fields and declared in my bean)
Are there any comments or objects that allow this?
Solution
Just use @ jsonanysetter This is its purpose This is a test case
public class JacksonTest {
public static class Bean {
private String name;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
private Map<String,Object> unrecognizedFields = new HashMap<>();
@JsonAnyGetter
public Map<String,Object> getUnrecognizedFields() {
return this.unrecognizedFields;
}
@JsonAnySetter
public void setUnrecognizedFields(String key,Object value) {
this.unrecognizedFields.put(key,value);
}
}
private final String json
= "{\"name\":\"paul\",\"age\":600,\"nickname\":\"peeskillet\"}";
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void testDeserialization() throws Exception {
final Bean bean = mapper.readValue(json,Bean.class);
final Map<String,Object> unrecognizedFields = bean.getUnrecognizedFields();
assertEquals("paul",bean.getName());
assertEquals(600,unrecognizedFields.get("age"));
assertEquals("peeskillet",unrecognizedFields.get("nickname"));
}
}
@Jsonanygetter is used to serialize aspects When serializing beans, you will not see unrecognized fields. Fields in JSON Instead, all attributes in the map will be serialized as top - level attributes in JSON
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
