日期:2014-05-17  浏览次数:20694 次

Struts2返回JSON后访问内部数据出错!
Action:
Java code
package com.trafic.action;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.trafic.bean.Accident;
import com.trafic.service.AccidentService;

public class GetAccidentPointsAction extends ActionSupport {

    private static final long serialVersionUID = 3511462933996799995L;

    private AccidentService as;
    private String validate;

    public void setAs(AccidentService as) {
        System.out.println("setAs...");
        this.as = as;
    }

    public String getValidate() {
        return validate;
    }

    public void setValidate(String validate) {
        this.validate = validate;
    }

    @Override
    public String execute() throws Exception {
        List<Accident> all = as.getAllAccident();
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"points\":[{");
        for (int i = 0; i < all.size(); i++) {
            if (i != all.size() - 1) {
                jsonBuilder.append("\"x\":" + all.get(i).getAcc_x() + ",\"y\":"
                        + all.get(i).getAcc_y() + "},{");
            } else {
                jsonBuilder.append("\"x\":" + all.get(i).getAcc_x() + ",\"y\":"
                        + all.get(i).getAcc_y() + "}]}");
            }
        }
        this.validate = jsonBuilder.toString();
        System.out.println(validate);
        return SUCCESS;
    }

}



我需要取得的是validate这个字符串组成的JSON:
期中validate字符串为:{"points":[{"x":123.0,"y":321.0}]}

在JSP中通过AJAX取得了该JSON;
问题就出现了:
JScript code

$.post("getAllAccident",function(validate){        
                alert(validate);//显示[Objext Object]
                [color=#FF0000]alert(validate.points[0].x); [/color]  这句话就不会弹出内容!为什么呢?
            })


我做了这个测试:
JScript code

var w = {"points":[{"x":123.0,"y":321.0}]};
alert(w); //弹出[Object Object]
alert(w.points[0].x); //弹出123


但是上面的访问也是按这个来的。怎么就会出错?
还是我JSON返回的就有问题?困惑了半天了,求大侠解答!谢谢

------解决方案--------------------
是个字符串,没有变成JSON对象;自己转换一次吧。

$.post("getAllAccident",function(validate){
validate = eval(validate.validate);
alert(validate.points[0].x);
})