如何将Java对象转换为JSON字符串?

下面的示例演示如何使用Jackson将Java对象转换为JSON字符串。Jackson provide ObjectMapper类提供了读写JSON数据的功能。writeValueAsString(Object)方法,用于将任何Java对象序列化为字符串。

package org.nhooo.example.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJson {

    public static void main(String[] args) {

        Artist artist = new Artist();

        artist.setId(1L);

        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();

        try {

            String json = mapper.writeValueAsString(artist);

            System.out.println("JSON = " + json);

        } catch (JsonProcessingException e) {

            e.printStackTrace();

        }

    }

}

运行上面的代码片段将打印出以下结果:

JSON = {"id":1,"name":"The Beatles"}

这是Artist类的定义。

package org.nhooo.example.jackson;

public class Artist {

    private Long id;

    private String name;

    public Artist() {

    }

    public Artist(Long id, String name) {

        this.id = id;

        this.name = name;

    }

    // Getters & Setters

    @Override

    public String toString() {

        return "Artist{" +

            "id=" + id +

            ", name='" + name + '\'' +

            '}';

    }

}

Maven依赖

<!-- http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.8.6/jackson-core-2.8.6.jar -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-core</artifactId>

    <version>2.8.6</version>

</dependency>

<!-- http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.8.6/jackson-annotations-2.8.6.jar -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-annotations</artifactId>

    <version>2.8.6</version>

</dependency>

<!-- http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.6/jackson-databind-2.8.6.jar -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.8.6</version>

</dependency>

                       

以上是 如何将Java对象转换为JSON字符串? 的全部内容, 来源链接: utcz.com/z/337937.html

回到顶部