How to convert POJO to JSON and vice versa?

前端 未结 6 749
忘了有多久
忘了有多久 2020-11-27 15:40

I want to know if there is any Java API available to convert a POJO object to a JSON object and vice versa.

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 16:28

    Take below reference to convert a JSON into POJO and vice-versa

    Let's suppose your JSON schema looks like:

    {
      "type":"object",
      "properties": {
        "dataOne": {
          "type": "string"
        },
        "dataTwo": {
          "type": "integer"
        },
        "dataThree": {
          "type": "boolean"
        }
      }
    }
    

    Then to covert into POJO, your need to decleare some classes as explained in below style:

    ==================================
    package ;
    public class DataOne
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class DataTwo
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class DataThree
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class Properties
    {
        private DataOne dataOne;
    
        private DataTwo dataTwo;
    
        private DataThree dataThree;
    
        public void setDataOne(DataOne dataOne){
            this.dataOne = dataOne;
        }
        public DataOne getDataOne(){
            return this.dataOne;
        }
        public void setDataTwo(DataTwo dataTwo){
            this.dataTwo = dataTwo;
        }
        public DataTwo getDataTwo(){
            return this.dataTwo;
        }
        public void setDataThree(DataThree dataThree){
            this.dataThree = dataThree;
        }
        public DataThree getDataThree(){
            return this.dataThree;
        }
    }
    
    ==================================
    package ;
    public class Root
    {
        private String type;
    
        private Properties properties;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
        public void setProperties(Properties properties){
            this.properties = properties;
        }
        public Properties getProperties(){
            return this.properties;
        }
    }
    

提交回复
热议问题