Jackson - Java bean to JSON string : uppercase variable converted into lowercase in JSON

前端 未结 2 432
后悔当初
后悔当初 2021-01-03 13:44

I am converting Java bean to JSON string using writeValueAsString method of ObjectMapper where uppercase variables from Java bean is being changed to lowercase in JSON strin

相关标签:
2条回答
  • 2021-01-03 14:06

    Following jars have been used:

    1. jackson-core-2.7.4.jar
    2. jackson-annotations-2.7.4.jar
    3. jackson-databind-2.7.4.jar

    Step 1: Please write following Mixin as follows:

    import java.util.ArrayList;
    import com.fasterxml.jackson.annotation.JsonProperty;
    
    public abstract class MixIn {
        @JsonProperty("PNRNumber")
        abstract String getPNRNumber();
    
        @JsonProperty("XId")
        abstract int getXId();
    
        @JsonProperty("minPriced")
        abstract ArrayList getMinPriced();
    }
    

    Step 2: Please write your Module as follows:-

    import com.fasterxml.jackson.databind.module.SimpleModule;
    
    public class MyModule extends SimpleModule{
      public MyModule() {
        super("ModuleName");
      }
      @Override
      public void setupModule(SetupContext context){
        context.setMixInAnnotations(BaseBean.class, MixIn.class);   
      }
    }
    

    Step 3: Now its time to get json String as follows:

    TermBean bean1=new TermBean("JSON");
    TermBean bean2=new TermBean("simple");
    ArrayList list=new ArrayList();
            list.add(bean1);
            list.add(bean2);
    BaseBean bb=new BaseBean();
            bb.setXId(11);
            bb.setPNRNumber("123456789");
            bb.setMinPriced(list);
    
    ObjectMapper mapper = new ObjectMapper();
    Module myModule = new MyModule();
    mapper.registerModule(myModule);        
    String jsonInString = mapper.writeValueAsString(bb);      
    System.out.printf( "JSON: %s", jsonInString ); 
    

    Output:

    JSON: {"XId":11,"PNRNumber":"123456789","minPriced":[{"name":"JSON"},{"name":"simple"}]}

    Hope this helps.

    0 讨论(0)
  • 2021-01-03 14:23

    Add Json Property with required keycase. Create variable with lowercase.

    public class BaseBean {
    
    @JsonProperty("XId")
    private int xId;
    ..
    }
    

    Hope this will help

    0 讨论(0)
提交回复
热议问题