jackson 進行json與java對象轉換 之四

來源:互聯網
上載者:User

標籤: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 maybeList<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對象轉換 之四

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.