一间杂货铺~

03月 12

一处JSON处理上的小细节


直接说JSON,感觉语义不太明确,最好还是说成JSON对象JSON字符串

假设前端通过ajax回调函数接收数据,参数名为data

$.post(
        "/xxx/yyy.do",
        $("#zzz-form").serialize(),
        function (data) {
            // to do something
        }
);

I. JSON对象

Content-Type被设置为application/json时:

resp.setContentType("application/json; charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
    out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}");
    out.flush();
}

前端收到的就是JSON对象,可以直接获取里面的属性:

function (data) {
    var reason = data.reason;
}

II. JSON字符串

Content-Type不是application/json时,比如是text/plain

resp.setContentType("text/plain; charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
    out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}");
    out.flush();
}

前端收到的就是JSON字符串,此时需要将其解析为JSON对象

function (data) {
    var json = JSON.parse(data);
    var reason = json.reason;
}

标签:json

还不快抢沙发

添加新评论