Home > Software engineering >  MappingJackson2HttpMessageConverter fails to convert json to entity
MappingJackson2HttpMessageConverter fails to convert json to entity

Time:10-02

I am using spring boot. RestTemplate. MappingJackson2HttpMessageConverter

MappingJackson2HttpMessageConverter fails to convert following json to entity. It does not throw any error. I am trying to debug the same. Whats wrong with Json ? and how do I enable failure for MappingJackson2HttpMessageConverter

    {
      "id" : 1,
      "context" : "MYC",
      "my_date" : "2021-06-20",
      "files" : [ {
        "file_name" : "here.txt",
        "created_time" : "2021-06-20T12:00:00 02:00"
      } ]
    }

Entity setter/getter are present

    public class Details{
    
        private Long id;
    
        private LocalDate myDate;
    
        private ContextEnum context;
    
        private List<FileInfo> files;
    }
public class FileInfo {
    private String fileName;

    private OffsetDateTime createdTime;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

CodePudding user response:

I assume it is because of JSON key are Snake Case but class field names in Camel Case. You can fixed this by three ways,

  1. Rename field names to match JSON object
  2. Annotate setter methods with @JsonProperty annotation.
  3. Annotate classes with @JsonNaming annotation

Method 2

public class Details{
    private Long id;
    private LocalDate myDate;
    private ContextEnum context;
    private List<FileInfo> files;

    @JsonProperty("my_date")
    public void setMyDate(LocalDate myDate) {
        this.myDate = myDate;
    }
}

public class FileInfo {
    private String fileName;
    private OffsetDateTime createdTime;

    @JsonProperty("file_name")
    public String getFileName() {
        return fileName;
    }

    @JsonProperty("created_time")
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

Method 3

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Details{
    private Long id;
    private LocalDate myDate;
    private ContextEnum context;
    private List<FileInfo> files;
}

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class FileInfo {
    private String fileName;
    private OffsetDateTime createdTime;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
  • Related