一 lombok 使用。
package org.com.d5;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
private String name;
private int age;
}
二 Gson 的使用。
去 mvn 仓库 mvnrepository.com/ 找依赖,放入pom
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
package org.com.d5;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
Gson gson = new Gson();
List<Student> stus = new ArrayList<Student>();
Student stu = new Student("xxx", 3);
stus.add(stu);
System.out.println(gson.toJson(stus));
System.out.println(gson.toJson(stu));
}
}