日期:2014-05-16 浏览次数:20734 次
JsonObject json1 = new JsonObject();
JsonObject json2 = new JsonObject();
json1.addProperty("id", 1);
json1.addProperty("name", "张三");
json2.addProperty("id", 2);
json2.addProperty("name", "李四");
List <JsonObject> list = new ArrayList <JsonObject>();
list.add(json1);
list.add(json2);
return list.toArray();//传到前台js中,可以正常得到对象
UserAction.getUser(function(result) {
alert(result);//这里可以得到值,提示的信息为:[object Object],[object Object]
alert(result.length);//这里得到的值为2,即数组长度为2,也正确
for (var i = 0; i < result.length; i++)
{
var item = result[i];
alert(item);//这里得到的值为[object Object]也正确
alert(item.name);//[color=#FF0000]这里为何得不到值?即得不到张三与李四呢?提示信息为:undefined[/color] }
}
 for (var i = 0; i < result.length; i++) 
        {
            var item = result[i];
            alert(item);//这里得到的值为[object Object]也正确
            alert(item.name);
//============加下面的语句测试下item里面有什么属性,怕是你的框架修改过json对象属性什么了的
for(attr in item)alert(attr+'='+item[attr]);
       }
   }
------解决方案--------------------
js和java中的json对象无法互相转换的吧(用struts2可以),可以在java中将对象转换为json字符串,传到js后,再在js中将json字符串转换成json对象
Map map1 = new HashMap();
Map map2 = new HashMap();
map1.put("id", 1);
map1.put("name", "张三");
map2.put("id", 2);
map2.put("name","李四");
List list = new ArrayList();
list.add(map1)
list.add(map2)
Map jsonMap = new HashMap();
jsonMap.put("jsonstr",list); //必须是map对象才能转换成json对象
JSONObject json = JSONObject.fromObject(map); //要用到json-lib-2.3-jdk15.jar
return json.toString();
 UserAction.getUser(function(result) {
 var jsonResult =  JSON.parse(result);//如何不行用var jsonResult=JSON.parseJSON(),json版本问题
var resultList = jsonResult['jsonstr'];
for(var one in resultList){
   var item= resultList[one];
    alert(item.id);
    alert(item.name);
}
------解决方案--------------------
 
alert(item.id);   //用item['id']也行
 alert(item.name); //用item['name']也行