1. 程式人生 > >json格式字串的list集合轉list物件集合

json格式字串的list集合轉list物件集合

1>方法一

//模擬json格式集合字串

String code = "[{"age":0,"jid":"0","name":"0"},{"age":1,"jid":"1","name":"1"},{"age":2,"jid":"2","name":"2"},{"age":3,"jid":"3","name":"3"},{"age":4,"jid":"4","name":"4"},{"age":5,"jid":"5","name":"5"},{"age":6,"jid":"6","name":"6"},{"age":7,"jid":"7","name":"7"},{"age":8,"jid":"8","name":"8"},{"age":9,"jid":"9","name":"9"}]";

//轉物件集合

List<User> list = JSONArray.toList(JSONArray.fromObject(code, User.class);

2>方法二(推薦使用)

使用com.alibaba.fastjson.JSON; 

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.9</version>

</dependency>

案例使用

//decode是集合字串

List<User> list = JSON.parseArray(code, User.class);

不指定泛型直接轉List<T>:

 ObjectMapper mapper = new ObjectMapper();
 List list = xxx.getXxx();
 List<User> users = mapper.convertValue(list, new TypeReference<List<User>>() { });

3>總結

 

使用方法一存在問題:轉實體的字串欄位必須與實體一一對應,侷限

 

使用方法二:轉實體字串欄位不需要與實體一一對應,實體有的欄位就會對應上,沒有的不會報錯

 

推薦使用二