所需jar包:
public class User { private int id; private String name; public User(){ } public User(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class Demo { public static void main(String[] args) { //将集合转成json List<User> user_list = new ArrayList<>(); user_list.add(new User(1, "盖伦")); user_list.add(new User(2, "鲁迅")); String list_json = Json.toJson(user_list, JsonFormat.compact()); System.out.println(list_json); //将对象转成json User user = new User(); user.setId(1); user.setName("张三"); String obj_json = Json.toJson(user, JsonFormat.compact()); System.out.println(obj_json); } }