Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

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)

1 Answer

0 votes
by (46k points)

What is required is to adjust getter method, NOT field -- field is private (and not auto-detected); besides, getters have precedence over fields if both are visible. (There are methods to make private fields visible, too, but if you want to hold getter there's not much point)

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

@JsonProperty("wrapper")

or, you can also mark the POJO to ignore unknown properties:

@JsonIgnoreProperties(ignoreUnknown = true)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...