0

I'd like to centrally configure jackson ObjectMapper and use everywhere in my app the same ObjectMapper. What could possible be wrong in the following code that the DI doesn't work?

I added a CustomJacksonConfig.java to src/main/java/migrationtool/config:

@Configuration
public class CustomJacksonConfig {

    @Bean
    public ObjectMapper mapper() {
        return new ObjectMapper();
    }

}

And use it within some class:

public abstract class HcmsEntity implements JsonSerializable {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public JsonNode serialize() {
           return this.mapper.valueToTree(this);
    }
}

Concrete Class:

   public class Paragraph extends HcmsComponent{
      @JsonWrapped("content") // module to be extended in the CustomJacksonConfig
      public String text;
   }

unit test :

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class ParagraphTest {

    @Test
    void serializeParagraph() {
        Paragraph paragraph = ParagraphMock.createParagraphWithID(1);
        paragraph.setIdentifier("p:1:1.p");

        assertThat(paragraph.serialize()).hasToString(ParagraphMock.getExpectedJson(1));

    }
 }

In the unittest which tests serialize()

10:08:00.693 [main] ERROR Paragraph - java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.ObjectMapper.valueToTree(Object)" because "this.mapper" is null

user66875
  • 2,772
  • 3
  • 29
  • 55
  • I'm guessing you're not running the unit test with the spring runner or extension (which depends on which version of junit you're using). Please include the unit test. – Rick Apr 01 '23 at 08:20
  • I've added the unittest – user66875 Apr 01 '23 at 08:32
  • 1
    What is `ParagraphMock.createParagraphWithID(..)`? Presumably it created an instance with `new` instead of through Spring, which means `mapper` is `null`. – Mark Rotteveel Apr 01 '23 at 09:15

0 Answers0