1.1.1 对象与JSON转化
@Test
public void toJSON() throws IOException{
Jedis jedis = new Jedis("192.168.126.174",6379);
User user = new User();
user.setId(100);
user.setName("json测试");
user.setAge(100);
user.setSex("男");
ObjectMapper objectMapper =
new ObjectMapper();
String userJSON =
objectMapper.writeValueAsString(user);
System.out.println(userJSON);
//将用户信息保存到redis中
jedis.set("user", userJSON);
String user_json = jedis.get("user");
//将json串转化为对象
User user2 =
objectMapper.readValue(user_json,User.class);
System.out.println(user2);
}
1.1.2 JSON与List集合转化
//将List集合转化json
@Test
public void listToJSON() throws IOException{
List<User> userList = new ArrayList<>();
for(int i=0;i<4;i++){
User user = new User();
user.setId(i);
user.setName("变形金刚"+i);
user.setAge(10+i);
user.setSex("男");
userList.add(user);
}
ObjectMapper objectMapper = new ObjectMapper();
String userListJSON =
objectMapper.writeValueAsString(userList);
System.out.println(userListJSON);
//将listJSON转化为集合
User[] users =
objectMapper.readValue(userListJSON, User[].class);
/*List<User> u_list =
objectMapper.readValue(userListJSON,userList.getClass());*/
System.out.println(Arrays.asList(users));
}
1.1.1 获取json中的属性
@Test
public void getJSON() throws IOException{
List<User> userList = new ArrayList<>();
for(int i=0;i<4;i++){
User user = new User();
user.setId(i);
user.setName("变形金刚"+i);
user.setAge(10+i);
user.setSex("男");
userList.add(user);
}
ObjectMapper objectMapper = new ObjectMapper();
String userListJSON =
objectMapper.writeValueAsString(userList);
System.out.println(userListJSON);
//读取json 获取json中下标为2的元素
JsonNode jsonNode =
objectMapper.readTree(userListJSON).get(2);
System.out.println(jsonNode);
//获取json属性值
String name = jsonNode.get("name").asText();
System.out.println("获取json串中的值:"+name);
}