JSON 字符串 与 java,js 对象的转换

JSON 字符串 与 java 对象的转换(2012-03-23 12:30:09)

jsonLib 经典文章:http://json-lib.sourceforge.net/xref-test/net/sf/json/TestJSONObject.html

转自:http://blog.sina.com.cn/s/blog_5920510a01011vu8.html

// 引入相应的包

//json-lib-2.2-jdk15.jar

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

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

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

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

  JSONObject object = JSONObject.fromObject(invite);
  String str=object.toString();

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

  String personstr = getRequest().getParameter("persons");
  JSONArray json = JSONArray.fromObject(personstr);
  List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, InvoidPerson.class);
4.遍历JSON对象数组

   JSONArray array = JSONArray.fromObject(jsonstr);

   //将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与js对象之间转换

相关文章:http://blog.csdn.net/wangxiaohu__/article/details/7254598

将json字符串(单个对象)转换成js对象:

var xxx=JSON.parse(xmlhttp.responseText);//xmlhttp返回的是一个自定义对象的Json字符串。
将js对象转换成json字符串:
var s= new Object();
 s.Id=id;
 s.Name=document.getElementById("name").value;
 s.Sex=document.getElementById("sex").value;
 s.Phone=document.getElementById("tel").value;
 s.Address=document.getElementById("address").value;
 s.Constellation=document.getElementById("star").value;
 var data= JSON.stringify(s);

将json字符串(对象数组)转换成js对象数组:

var xxx1=eval(xmlhttp.responseText);//xmlhttp返回的是一个自定义对象列表的Json字符串。
用xxx1[i].prop就可以得到第i个对象的某个属性。

将js数组j转换成json字符串(对象数组)

 

posted @ 2012-12-24 16:52  方子格  阅读(931)  评论(0编辑  收藏  举报