1 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2 实体类-用户User
@Data
@AllArgsConstructor
class User{
private String id;
private String name;
}
3 List与Json字符串互转
3.1 实体类列表
public static void main(String[] args) {
User user1 = new User("001", "用户1");
User user2 = new User("002", "用户2");
User user3 = new User("003", "用户3");
User user4 = new User("004", "用户4");
User user5 = new User("005", "用户5");
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
}
3.2 List -> Json String
// List<User> -> Json String
String s = JSON.toJSONString(list);
System.out.println(s);
输出
[{"id":"001","name":"用户1"},{"id":"002","name":"用户2"},{"id":"003","name":"用户3"},{"id":"004","name":"用户4"},{"id":"005","name":"用户5"}]
3.3 Json String->List
// Json String -> List<User>
List<User> users = JSON.parseArray(s, User.class);
System.out.println(users);
输出
[User(id=001, name=用户1), User(id=002, name=用户2), User(id=003, name=用户3), User(id=004, name=用户4), User(id=005, name=用户5)]