码迷,mamicode.com
首页 > 编程语言 > 详细

jackson 进行json与java对象转换 之四

时间:2017-05-18 12:39:52      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:turn   ash   ide   习惯   actor   简单   stty   getname   ble   

jackson简单使用,对象转json,json转对象,json转list

 

POJO序列化为json字符串:

准备一个POJO:

技术分享
@JsonIgnoreProperties(ignoreUnknown = true)
class User implements Serializable {
    private static final long serialVersionUID = -5952920972581467417L;
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name=" + name +
                ‘}‘;
    }
}
技术分享
  • @JsonIgnoreProperties(ignoreUnknown = true) 是为了反序列化的时候,如果遇到不认识的filed,忽略之
  • 无参构造函数是为了在反序列化的时候,jackson可以创建POJO实例
  • getter方法是为了序列化的时候,jackson可以获取filed值
  • toString是方便我自己debug看显示
  • 至于Serializable,习惯的给实体增加一个持久化的能力。

通过write来转化成jason字符串:

String expected = "{\"name\":\"Test\"}";
String test = mapper.writeValueAsString(new User("Test"));
Assert.assertEquals(expected, test);

通过read来parse json字符串为POJO对象:

User user = mapper.readValue(expected, User.class);
Assert.assertEquals("Test", user.getName());

 

 

jsonArray转换成Array数组:

String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]";
ArrayType arrayType = mapper.getTypeFactory().constructArrayType(User.class);
User[] users = mapper.readValue(expected, arrayType);
Assert.assertEquals("Ryan", users[0].getName());

 

jsonArray转换成List<>泛型:

技术分享
expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class);
//the sieze of the list is dependon the str json length although the json content is not the POJO type maybe
List<User> userList = mapper.readValue(expected, listType);
Assert.assertEquals(3, userList.size());
Assert.assertNull(userList.get(0).getName());
Assert.assertEquals("Ryan",userList.get(2).getName());
技术分享

 

jackson默认将对象转换为LinkedHashMap:

String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]";
ArrayList arrayList = mapper.readValue(expected, ArrayList.class);
Object o = arrayList.get(0);
Assert.assertTrue(o instanceof LinkedHashMap);

 转载:http://www.cnblogs.com/woshimrf/p/5847262.html

 

jackson 进行json与java对象转换 之四

标签:turn   ash   ide   习惯   actor   简单   stty   getname   ble   

原文地址:http://www.cnblogs.com/cainiao-Shun666/p/6872678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!