【问题标题】:How to convert POJO to JSON and vice versa?如何将 POJO 转换为 JSON,反之亦然?
【发布时间】:2012-03-24 12:06:34
【问题描述】:

我想知道是否有任何 Java API 可用于将 POJO 对象转换为 JSON 对象,反之亦然。

【问题讨论】:

    标签: java json pojo


    【解决方案1】:

    看看https://www.json.org

    假设您有一个像这样的简单 Java 类:

    public class Person {
    
        private String name;
        private Integer age;
    
        public String getName() { return this.name; }
        public void setName( String name ) { this.name = name; }
    
        public Integer getAge() { return this.age; }
        public void setAge( Integer age ) { this.age = age; }
    
    }
    

    因此,要将其转换为 JSON 对象,非常简单。像这样:

    import org.json.JSONObject;
    
    public class JsonTest {
    
        public static void main( String[] args ) {
            Person person = new Person();
            person.setName( "Person Name" );
            person.setAge( 333 );
            
            JSONObject jsonObj = new JSONObject( person );
            System.out.println( jsonObj );
        }
    
    }
    

    这里还有另一个例子,在本例中使用 Jackson:https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/

    马文:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.1</version>
    </dependency>
    

    还有一个链接(如下)可以找到最新/最好的版本:

    https://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22com.fasterxml.jackson.core%22%20AND%20a%3A%22jackson-databind%22

    【讨论】:

    • Thnx 但是...我希望如果我有一个 Pojo,我可以传递 pojo 对象,这样库就可以构造 JSON 对象... gson 可以这样做吗?你能给我一个例子吗?非常感谢
    • @Bruno 我们如何使用这个 JSONObject 获取 List 或 Set 的值。
    • 我喜欢这种方法 - 不幸的是它对我不起作用。我收到错误消息:“构造函数 JSONObject(Person) 未定义”.. 知道为什么吗?我在一些Android代码中调用它..它是纯Java。谢谢
    • @gnB:即使我也遇到同样的错误,我想如果你在 android 中尝试,那么它指的是 developer.android.com/reference/org/json/JSONObject.html 。所以尝试创建json.org/javadoc/org/json/JSONObject.html的对象
    【解决方案2】:

    参考以下内容将 JSON 转换为 POJO,反之亦然

    假设您的 JSON 架构如下所示:

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

    然后要转换为 POJO,您需要清除一些类,如下所示:

    ==================================
    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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用jackson api进行转换

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
      </dependency>
      

      在你的 POM 中添加上面的 maven 依赖,在你的 main 方法中创建 ObjectMapper

      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      

      稍后我们需要将 POJO 类添加到映射器中

      String json = mapper.writeValueAsString(pojo);
      

      【讨论】:

        【解决方案4】:

        使用 GSON 将 POJO 转换为 JSONObject。 Refer here.

        JSONObject转POJO只需调用POJO中的setter方法,直接从JSONObject中赋值即可。

        【讨论】:

          【解决方案5】:

          如果您知道 Jackson 2mkyong.com 上有一个很棒的教程,介绍如何将 Java 对象转换为 JSON,反之亦然。以下代码 sn-ps 取自该教程。

          将 Java 对象转换为 JSON,writeValue(...):

          ObjectMapper mapper = new ObjectMapper();
          Staff obj = new Staff();
          
          //Object to JSON in file
          mapper.writeValue(new File("c:\\file.json"), obj);
          
          //Object to JSON in String
          String jsonInString = mapper.writeValueAsString(obj);
          

          将 JSON 转换为 Java 对象,readValue(...):

          ObjectMapper mapper = new ObjectMapper();
          String jsonInString = "{'name' : 'mkyong'}";
          
          //JSON from file to Object
          Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
          
          //JSON from URL to Object
          Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
          
          //JSON from String to Object
          Staff obj = mapper.readValue(jsonInString, Staff.class);
          

          Jackson 2 依赖:

          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-databind</artifactId>
              <version>2.6.3</version>
          </dependency>
          

          完整的教程,请访问上面给出的链接。

          【讨论】:

            【解决方案6】:

            我们还可以在您的 pom 文件中使用以下给定的依赖项和插件 - 我使用 maven。通过使用这些,您可以根据您的 JSON 模式生成 POJO,然后使用下面给出的代码通过指定为 gson.toJson(Object src) 参数的 src 对象填充请求 JSON 对象,反之亦然。看下面的代码:

            Gson gson = new GsonBuilder().create();
            String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());
            
            Gson gson2 = new Gson();
            Error expectederr = gson2.fromJson(payloadStr, Error.class);
            

            还有 Maven 设置:

            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>1.7.1</version>
            </dependency>
            
            <plugin>
                <groupId>com.googlecode.jsonschema2pojo</groupId>
                <artifactId>jsonschema2pojo-maven-plugin</artifactId>
                <version>0.3.7</version>
                <configuration>
                    <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
                    <targetPackage>com.example.types</targetPackage>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-05-10
              • 1970-01-01
              • 1970-01-01
              • 2013-08-09
              • 1970-01-01
              相关资源
              最近更新 更多