public class JsonTest {
//准备存放了一个对象的json字符串
private String userStr = "{\"id\":1,\"name\":\"简溪\",\"birthday\":\"2010-01-01\"}";
//准备存放了一个集合的json字符串
private String userArr = "[{\"id\":1,\"name\":\"简溪\",\"birthday\":\"2010-01-01\"},"+ "{\"id\":2,\"name\":\"顾里\",\"birthday\":\"2012-08-01\"}]";
private User user;
private List<User> users = new ArrayList<User>();
@Before
public void initUser() {
//初始化一个用户
User user = new User();
user.setId(1);
user.setName("林萧");
user.setBirthday(new Date());
this.user = user;
//初始化一个集合
User user1 = new User();
user1.setId(1);
user1.setName("林萧");
user1.setBirthday(new Date());
users.add(user1);
User user2 = new User();
user2.setId(2);
user2.setName("顾源");
user2.setBirthday(new Date());
users.add(user2);
}
//fastjson
@Test
public void fastjson_json2Bean() {
//[1-1] 对象格式json串转对象
User user = JSONObject.parseObject(userStr, User.class);
System.out.println(user);
//打印效果如下:
//User [id=1, name=简溪, birthday=2010-01-01]
//[1-2] 集合格式json串转对象
List<User> users = JSONArray.parseArray(userArr, User.class);
System.out.println(users);
//打印效果如下:
// [User [id=1, name=简溪, birthday=2010-01-01], User [id=2, name=顾里, birthday=2012-08-01]]
}
@Test
public void fastjson_bean2Json() {
//[1-3] 对象转json串
String userJson = JSONObject.toJSONString(user);
System.out.println(userJson);
//打印效果如下:
// {"birthday":1530716739741,"id":1,"name":"林萧"}
//[1-4] 集合转json串
String usersStr = JSONArray.toJSONString(users);
System.out.println(usersStr);
//打印效果如下:
// [{"birthday":1530716739741,"id":1,"name":"林萧"},{"birthday":1530716739741,"id":2,"name":"顾源"}]
}
//jackson
@Test
public void jackson_json2Bean() throws Exception {
//[2-1] 对象格式json串转对象
ObjectMapper jackson = new ObjectMapper();
User user = jackson.readValue(userStr, User.class);
System.out.println(user);
//打印结果
//User [id=1, name=简溪, birthday=2010-01-01]
//[2-2 对象格式json串转对象
List<User> users = jackson.readValue(userArr, new TypeReference<List<User>>() {});
System.out.println(users);
//打印结果
//[User [id=1, name=简溪, birthday=2010-01-01], User [id=2, name=顾里, birthday=2012-08-01]]
}
@Test
public void jackson_bean2Json() throws Exception {
ObjectMapper jackson = new ObjectMapper();
//[2-3] 对象转json串
String userJson = jackson.writeValueAsString(user);
System.out.println(userJson);
//打印结果
// {"id":1,"name":"林萧","birthday":1530717373507}
//[2-4] 集合转json串
String usersJson = jackson.writeValueAsString(users);
System.out.println(usersJson);
//打印结果
// [{"id":1,"name":"林萧","birthday":1530717401460},{"id":2,"name":"顾源","birthday":1530717401460}]
}
}