json对象的运用

1、js前端中json对象之间的转换

字符串转对象(strJSON代表json字符串)
  var obj = eval(strJSON);
  var obj = strJSON.parseJSON();
  var obj = JSON.parse(strJSON);
json对象转字符串(obj代表json对象)
  var str = obj.toJSONString();
  var str = JSON.stringify(obj)
运用时候需要除了eval()以外需要json.js包

2、java后台json对象之间的转换

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

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

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

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

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

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

  String personstr = getRequest().getParameter("persons");
  JSONArray json = JSONArray.fromObject(personstr);
  List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);
d.//把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字符串中一个json集合字符串

   String jsonStr = jsonobject.getString("passports");

   jsonStr = jsonStr.substring(1,jsonStr.length-1);   //去掉外层的双引号
   //获取一个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);

相关推荐