Java實(shí)體類轉(zhuǎn)換為JSON的方法有多種,可以使用以下幾種方式:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
然后可以使用ObjectMapper
類將實(shí)體類轉(zhuǎn)換為JSON字符串,示例代碼如下:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
MyClass obj = new MyClass();
String json = objectMapper.writeValueAsString(obj);
System.out.println(json);
}
}
class MyClass {
private String name = "John";
private int age = 30;
// getter and setter methods
}
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
然后可以使用Gson
類將實(shí)體類轉(zhuǎn)換為JSON字符串,示例代碼如下:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
MyClass obj = new MyClass();
String json = gson.toJson(obj);
System.out.println(json);
}
}
class MyClass {
private String name = "John";
private int age = 30;
// getter and setter methods
}
以上是兩種常用的方式,你可以根據(jù)自己的需求選擇其中一種進(jìn)行實(shí)體類轉(zhuǎn)JSON。