首页 > 编程语言 > 详细

JSON字符串与java对象的转换

时间:2014-07-17 18:09:46      阅读:245      评论:0      收藏:0      [点我收藏+]

所需的jar包: 

1、commons-lang.jar 
2、commons-beanutils.jar 
3、commons-collections.jar 
4、commons-logging.jar 
5、ezmorph.jar 
6、json-lib-2.2.2-jdk15.jar

1. 把java 对象列表转换为json对象数组,并转为字符串

JSONArray array = JSONArray.fromObject(userlist);
String jsonstr = array.toString();

2.把java对象转换成json对象,并转化为字符串

JSONObject object = JSONObject.fromObject(invite);
Log4jInit.ysulogger.debug(object.toString());

3.把JSON字符串转换为JAVA 对象数组

String personstr = getRequest().getParameter("persons");
JSONArray json = JSONArray.fromObject(personstr);
List
<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);

4.把JSON字符串转换为JAVA 对象

str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",
          \"lenddate\":\"2010-07-19T00:00:00\",\"lendcounts\":4,\"
              passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
                 {\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
                      {\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
                          {\"passportid\":\"K905199\",\"name\":\"贺明\",\"passporttype\":\"K\"}]}";
JSONObject jsonobject = JSONObject.fromObject(str);
PassportLendsEntity passportlends = null;
try {
   //获取一个json数组
   JSONArray array = jsonobject.getJSONArray("passports");
   //将json数组 转换成 List<PassPortForLendsEntity>泛型
   List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
   for (int i = 0; i < array.size(); i++) {   
            JSONObject object = (JSONObject)array.get(i);  
            PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
              PassPortForLendsEntity.class);
            if(passport != null){
             list.add(passport);
            }  
   }
//转换PassportLendsEntity 实体类
passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);

JSON字符串与java对象的转换,布布扣,bubuko.com

JSON字符串与java对象的转换

原文:http://www.cnblogs.com/dreammyle/p/3851307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!