Java对象转换为JSON的方法分享
下文笔者讲述Java对象转JSON的方法分享,如下所示
JSON
JSON对象有利于数据传输
那么如何将一个对象转换为JSON字符串呢?下文笔者将一一道来,如下所示
对象转JSON的实现思路
1.引入相关依赖
gson
2.创建JSONObject对象
3.使用JSONObject对象中的object 将对象转换一个object对象
4.使用object.toString()方法获取 JSON 字符串
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.java265.javaobjectjson</groupId>
<artifactId>JavaObjectJSON</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
</dependencies>
</project>
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.util.Arrays;
public class PojoToJSON {
public static void main(String[] args) throws JsonProcessingException {
Student student = new Student();
student.setId(2L);
student.setName("test");
student.setAge(16);
student.setCourses(Arrays.aslist("java265.com-1", "java265.com-2", "java265.com-3"));
JSONObject object = new JSONObject(student);
String json = object.toString();
System.out.println(json);
System.out.println(new Gson().toJson(student));
// Creating Object of ObjectMapper define in Jackson API
ObjectMapper Obj = new ObjectMapper();
// Converting the Java object into a JSON string
String jsonStr = Obj.writeValueAsString(student);
// Displaying Java object into a JSON string
System.out.println(jsonStr);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


