简体   繁体   English

如何将 POJO 转换为 JSON,反之亦然?

[英]How to convert POJO to JSON and vice versa?

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

Take a look at https://www.json.org看看https://www.json.org

[edited] Imagine that you have a simple Java class like this: [已编辑] 想象一下,您有一个像这样的简单 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; }

}

So, to transform it to a JSon object, it's very simple.所以,要将其转换为 JSon 对象,非常简单。 Like this:像这样:

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

}

Hope it helps.希望能帮助到你。

[edited] Here there is other example, in this case using Jackson: https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/ [编辑] 这里还有其他例子,在这种情况下使用杰克逊: https : //brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/

Maven:马文:

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

And a link (below) to find the latest/greatest version:还有一个链接(下面)可以找到最新/最好的版本:

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

If you are aware of Jackson 2 , there is a great tutorial at mkyong.com on how to convert Java Objects to JSON and vice versa.如果您知道Jackson 2 ,那么mkyong.com上有一个很棒的教程,介绍如何将 Java 对象转换为 JSON,反之亦然。 The following code snippets have been taken from that tutorial.以下代码片段取自该教程。

Convert Java object to JSON, writeValue(...) :将 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);

Convert JSON to Java object, readValue(...) :将 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:杰克逊 2 依赖:

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

For the full tutorial, please go to the link given above.有关完整教程,请转到上面给出的链接。

We can also make use of below given dependency and plugin in your pom file - I make use of maven.我们还可以在您的 pom 文件中使用以下给定的依赖项和插件 - 我使用 maven。 With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa.通过使用这些,您可以根据您的 JSON 模式生成 POJO,然后使用下面给出的代码通过指定为 gson.toJson(Object src) 参数的 src 对象填充请求 JSON 对象,反之亦然。 Look at the code below:看看下面的代码:

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());

Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);

And the Maven settings:和 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>

You can use jackson api for the conversion您可以使用 jackson api 进行转换

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

add above maven dependency in your POM, In your main method create ObjectMapper在您的 POM 中添加上述 maven 依赖项,在您的主要方法中创建 ObjectMapper

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

later we nee to add our POJO class to the mapper稍后我们需要将我们的 POJO 类添加到映射器

String json = mapper.writeValueAsString(pojo);

Take below reference to convert a JSON into POJO and vice-versa请参考以下参考将 JSON 转换为 POJO,反之亦然

Let's suppose your JSON schema looks like:假设您的 JSON 架构如下所示:

{
  "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:然后要转换到 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;
    }
}

Use GSON for converting POJO to JSONObject.使用 GSON 将 POJO 转换为 JSONObject。 Refer here. 参考这里。

For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.要将 JSONObject 转换为 POJO,只需调用 POJO 中的 setter 方法并直接从 JSONObject 分配值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM