java – 杰克逊在地图中捕捉到无法识别的字段

我在java Rest Api中使用Jackson来处理请求参数.

我的班级:

public class ZoneModifBeanParam extends ModifBeanParam<Zone> {
@FormParam("type")
private String type;

@FormParam("geometry")
private Geometry geometry;

@FormParam("name")
private String name;

...

我的API界面:

@POST
@Consumes("application/json")
@Produces("application/json; subtype=geojson")
@ApiOperation(value = "Create a zone", notes = "To create a zone")
public Response createZone(ZoneModifBeanParam zoneParam) {

...

这工作正常,但我需要接收我的Bean在地图中未指定的其他参数.
示例:

{
   "geometry": {...},
   "name": "A circle name",
   "type": "4",
   "hello": true
}

通过接收这个我需要存储在一个Map(名为unrecognizedFields并在我的bean中声明)这对夫妇(“你好”,真实).

是否有任何注释或对象允许这个?

解决方法:

只需使用@JsonAnySetter.这就是它的用途.这是一个测试用例

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用于序列化方面.序列化bean时,您将看不到JSON中的unrecognizedFields.相反,地图中的所有属性都将序列化为JSON中的*属性.

上一篇:java – 将URI路径传递给JAX-RS提供程序


下一篇:java-泽西岛2杰克逊注释/ @JsonIgnore