0

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?

Jason
  • 2,495
  • 4
  • 26
  • 37

2 Answers2

0

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

Jason
  • 2,495
  • 4
  • 26
  • 37
  • https://www.baeldung.com/jackson-field-serializable-deserializable-or-not says that a public setter works. But https://stackoverflow.com/questions/48641620/make-jackson-deserialize-into-private-fields-without-setter-or-constructor says you can do it without if you write a custom deserializer. – Jerry Jeremiah Jul 07 '21 at 21:46
0

I had the same problem in a Maven Kotlin project and solved it by added the dependency:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.15.2</version>
</dependency>
cheb1k4
  • 2,316
  • 7
  • 26
  • 39