奇怪"找不到JSONObject"错误

时间:2014-08-20 15:21:27

标签: java javascript json httprequest

我正面临来自HTTP Request body的JSON转换问题。 首先,这是发送请求的Javascript代码。

例如,

object变量可以是{"view":"global"}

var sendHttpRequest = function (url, object)
{
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/json; charset=UTF-8");
    var json = JSON.stringify(object);
    xmlhttp.send(json);
};

然后是Java部分:

@Override
@RequestMapping(value = "/departments")
public 
@ResponseBody
void getJsonObject(HttpServletRequest request)
{
    StringBuilder jb = new StringBuilder();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null)
        jb.append(line);

    } catch (Exception e) {}

    JSONObject json = new JSONObject(jb.toString());

    String view = json.getString("view");
    ...
}

最后一行是引发此错误:

org.json.JSONException: JSONObject["view"] not found.

然而,如果我打印json变量,我会获得{"view":"global"},这似乎是正确的......

有人会有任何想法吗?

非常感谢!

编辑:

“未找到”问题是由于jb.toString()直接传递给JSONObject构造函数。这是编辑过的代码:

@Override
@RequestMapping(value = "/departments")
public 
@ResponseBody
void getJsonObject(HttpServletRequest request)
{
    StringBuilder jb = new StringBuilder();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null)
        jb.append(line);

    } catch (Exception e) {}

    String str = jb.toString();
    JSONObject json = new JSONObject(str);

    String view = json.getString("view");
    ...
}

但这次,错误是:

A JSONObject text must begin with '{' at 1 [character 2 line 1]

使用json硬编码,但不使用str变量。然而,它的印刷品似乎是正确的,没有空格:

{"view":"global"}

2 个答案:

答案 0 :(得分:1)

当我按如下方式运行您的代码时,

public static void main(String[] args) {
    String str = "{\"view\":\"global\"}";
    org.json.JSONObject json = new org.json.JSONObject(str);
    String view = json.getString("view");
    System.out.println(view);
}

我得到了

global

答案 1 :(得分:0)

您可以尝试使用TypeReference吗?

示例代码:

TypeReference<Map<String, String>> t=new TypeReference<Map<String, String>>(){};
ObjectMapper mapper = new ObjectMapper();
try {
    Map<String, String> data = mapper.readValue("{\"view\":\"global\"}", t);
    System.out.println(data.get("view")); // prints global
} catch (Exception e) {
    System.out.println("There might be some issue with the JSON string");
}

问题可能在于从客户端发送到服务器的编码字符串。正确解码后再试一次。

究竟JSON.stringify()究竟是什么?在服务器端打印JSON字符串作为SOP并尝试调试它。