1. pom依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
2. javaBean转json字符串
import com.google.gson.Gson;
public class Example {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(30);
person.setAddress("New York");
Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
}
}
class Person {
private String name;
private int age;
private String address;
// getters and setters
}
输出结果:
{"name":"John","age":30,"address":"New York"}