简单说下:
有一个json字符串,我想通过jackson把json字符串转换成list对象集合,网上找了很多,但都不尽人意。后来还是看jackson文档,才知道怎么做。
需要的包:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
要转换的json字符串:
[{"id":"36CD0224C1ED25F5E0538A3B0B7A8190","catgId":null,"matcAmont":50000,"lendPoolId":"36CD0224C1C225F5E0538A3B0B7A8190","balance":50000,"matchFlag":1,"isLock":1,"createTime":1467576000000,"userId":0,"mltCustLendPool":{"id":"36CD0224C1C225F5E0538A3B0B7A8190","userId":157020,"state":1,"isLock":1,"balance":50000,"curTotaAmt":50000,"syncDate":1467561600000,"inviFlag":2,"investTime":1467595065000,"deadline":1499131065000,"billDate":1467681465000,"billDay":5,"productId":"6","productName":"xxx","investAmt":50000,"prodOrderId":38662,"userTelephone":"15922166933","userName":"张三","idcardNum":"1111111111111","projectNum":null,"matchModelCode":null,"creditProduct":{"id":"290AA19B1134838EE053A716C0769130","swldid":"6","prodName":"xxx","prodType":null,"prodRate":0.13,"synFeeRate":null,"payCapitalType":null,"freezeTime":12,"prodCode":6,"prodCatgory":1,"unit":1},"subject":null},"orderFlag":null,"subject":0,"projectNum":null,"matchModeCode":"1"},{"id":"36DA5B50E54E2790E0538A3B0B7A2261","catgId":null,"matcAmont":50000,"lendPoolId":"36CD0224C1C225F5E0538A3B0B7A8190","balance":50000,"matchFlag":1,"isLock":1,"createTime":1467748800000,"userId":0,"mltCustLendPool":{"id":"36CD0224C1C225F5E0538A3B0B7A8190","userId":157020,"state":1,"isLock":1,"balance":50000,"curTotaAmt":50000,"syncDate":1467561600000,"inviFlag":2,"investTime":1467595065000,"deadline":1499131065000,"billDate":1467681465000,"billDay":5,"productId":"6","productName":"xxx","investAmt":50000,"prodOrderId":38662,"userTelephone":"15922166933","userName":"王dd","idcardNum":"2222222222222","projectNum":null,"matchModelCode":null,"creditProduct":{"id":"290AA19B1134838EE053A716C0769130","swldid":"6","prodName":"dfdfd","prodType":null,"prodRate":0.13,"synFeeRate":null,"payCapitalType":null,"freezeTime":12,"prodCode":6,"prodCatgory":1,"unit":1},"subject":null},"orderFlag":null,"subject":0,"projectNum":null,"matchModeCode":"1"}]
这个字符串的基本格式是数组型,也就是[{},{},{},{}]这种格式。
主要实现的代码不超过三行:
ObjectMapper mapper = new ObjectMapper();//定义 org.codehaus.jackson
//MltWaitLendReco 是你要转换的bean
List<MltWaitLendReco> lendReco =
mapper.readValue(listStr,new TypeReference<List<MltWaitLendReco>>() { });
//new TypeReference<List<MltWaitLendReco>>() { }写法很重要,写成List.class是不行的
System.out.println(lendReco.get(0).getId());
顺便把引入的类给写下:
import org.codehaus.jackson.type.TypeReference;
import org.codehaus.jackson.map.ObjectMapper;
其实这类json之间的转换工作中用到的很多,但没有总结过。还是有必要写个相关的工具类,总结下的。
为啥这么简单想不到呢?
---------------------
作者:第八个小矮人
来源:CSDN
原文:https://blog.csdn.net/qq_27751159/article/details/84854963