25.jackson与fastjson

jackson
SpringMVC默认整合.
jackson-annotations-2.9.2.jar
jackson-core-2.9.2.jar
jackson-databind-2.9.2.jar
(1开头的包对应spring4以前的版本,使用时需要注意)
使用示例代码:
@Test
//测试jackson 单个对象与json之间的相互转换
public void testJacksonSingle() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(new User(1L,"小林",18,new Date()));
    System.out.println(json);
    
    User user = mapper.readValue("{\"id\":1,\"name\":\"小海\"}", User.class);
    System.out.println(user);
}

@Test
//测试jackson 多个对象与json之间的相互转换
public void testJacksonList() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    
    List list = new ArrayList<>();
    list.add(new User(1L,"小林",18,new Date()));
    list.add(new User(2L,"林书",18,new Date()));
    list.add(new User(3L,"若愚",18,new Date()));
    String json = mapper.writeValueAsString(list);
    System.out.println(json);
    
    //javatype,获取类型工厂,用 构造器返回值类型
    //参数1.返回 值类型,参数2.返回值的泛型
    JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, User.class);
    
    List list2 = mapper.readValue(json, javaType);
    for (User user : list2) {
        System.out.println(user);
    }
}
fastjson:
@Test
//测试 fastjson 单个对象与json之间的相互转换
public void testFastJsonSingle() throws Exception {
    String jsonString = JSON.toJSONString(new User(5L,"姬長空",18,new Date()));
    System.out.println(jsonString);
    
    User user = JSON.parseObject(jsonString, User.class);
    System.out.println(user);
}

@Test
//测试 fastjson 单多个对象与json之间的相互转换
public void testFastJsonList() throws Exception {
    List list = new ArrayList<>();
    list.add(new User(1L,"小林",18,new Date()));
    list.add(new User(2L,"林书",18,new Date()));
    list.add(new User(3L,"若愚",18,new Date()));
    String json = JSON.toJSONString(list);
    System.out.println(json);
    
    List list2 = JSON.parseArray(json, User.class);
    for (User user : list2) {
        System.out.println(user);
    }
}

你可能感兴趣的:(25.jackson与fastjson)