JSON 字符串 与 java,js 对象的转换
JSON 字符串 与 java 对象的转换(2012-03-23 12:30:09)
转自: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对象:
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;
将json字符串(对象数组)转换成js对象数组:
将js数组j转换成json字符串(对象数组)