Search code examples
javajsonspringrequestdeserialization

Deserializing a JSON object that doesn't work if there are uppercase letters


I have that class

package com.akensys.testlucas.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Data;

@Entity
@Data
public class Vetement {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private int code;
    private String sku;
    }

In postman i send http://localhost:8081/user/addJSON :

{
    "code":1310695,
    "sku":"524080012403"
}

All its okay i have the code and sku : Vetement(id=null, code=1310695, sku=524080012403)

But if my JSON looks like that :

{
    "CODE":1310695,
    "SKU":"524080012403"
}

And if I modify my class : code to CODE and sku to SKU It still doesn't work I need to keep the JSON with name in uppercase so how can i make it works and why it doesnt work ?


Solution

  • I believe you are using Spring's default Jackson library. If so, fix it by configuring your application.yml like the following:

    spring:
      jackson:
        mapper:
          ACCEPT_CASE_INSENSITIVE_PROPERTIES: true
    

    via application.properties

      spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_PROPERTIES=true
    

    And finally, test your application well.



    You can also configure the same via Java configuration, like below:

        @Bean
        public ObjectMapper objectMapper() {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            return mapper;
        }
    

    (Note: method configure() is deprecated)



    If you are using the latest version of Spring, you can achieve the same via Java configuration, like below:

        @Bean
        public JsonMapper jsonMapper() {
            JsonMapper jm = JsonMapper.builder()
                    .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
                    .build();
            return jm;
        }