Search code examples
jsonjacksondeserializationjson-deserialization

Jackson cannot deserialize single field class, although Creator exists


I have the following simple jUnit test:

class MyTest {
 
   static class SingleField {
        int rank;
        SingleField(int rank) {
            this.rank = rank;
        }

        @Override
        public boolean equals(Object o) {
            if(!(o instanceof  SingleField)) {
                return  false;
            } else {
                return ((SingleField) o).rank == rank;
            }
        }
    }

   @Test
    public void testBasicJacksonParsing() throws JsonProcessingException {
        assertEquals(new SingleField(3), new ObjectMapper().readValue("{\"rank\" : 3}", SingleField.class));
    }
   
}

Unfortunately, when run, the test throws a MismatchedInputException with message:

Cannot construct instance of `com.drfirst.gear.user.context.util.AppUtilTest$SingleField` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"rank" : 3}"; line: 1, column: 2]

The accepted answer here seems to imply that one needs an all-args constructor. I clearly have one. I have also tried the same unit test by making the constructor of SingleField public, and I have also changed rank to String, making sure I also update the String I am parsing from "{\"rank\" : 3}" to "{\"rank\" : \"3\"}". Same Exception thrown.

Ideas on what I'm doing wrong here?


Solution

  • It turns out that I needed public setters for my fields.