Jackson with JSON: Unrecognized field, not marked as ignorable

I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

Here is a simplified use case:

private void tryReading() {
    String jsonStr = "{"wrapper":[{"id":"13","name":"Fred"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

My entity class is:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

My Wrapper class is basically a container object to get my list of students:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

I keep getting this error and "wrapper" returns null . I am not sure what's missing. Can someone help please?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

You can use Jackson's class-level annotation:

@JsonIgnoreProperties

It will ignore every property you haven't defined in your POJO. Very useful when you are just looking for a couple of properties in the JSON and don't want to write the whole mapping. More info at Jackson's website. If you want to ignore any non declared property, you should write:

@JsonIgnoreProperties(ignoreUnknown = true)

You can use

ObjectMapper objectMapper = getObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

It will ignore all the properties that are not declared.


The first answer is almost correct, but what is needed is to change getter method, NOT field -- field is private (and not auto-detected); further, getters have precedence over fields if both are visible.(There are ways to make private fields visible, too, but if you want to have getter there's not much point)

So getter should either be named getWrapper() , or annotated with:

@JsonProperty("wrapper")

If you prefer getter method name as is.

链接地址: http://www.djcxy.com/p/37866.html

上一篇: 如果杰克逊在序列化过程中忽略某个字段的值是否为空,该如何告诉他?

下一篇: 杰克逊与JSON:无法识别的字段,未标记为可忽略