将字符串转换为JSON对象错误解析数据

时间:2013-01-29 17:03:31

标签: android json parsing

我使用它在localhost上完美运行的代码,但是我尝试在我的网络服务器上执行操作,在从字符串解析为JSON对象时解析其显示的错误没有得到什么错误

我的JSON解析器代码是

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "utf-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    json = sb.toString();
    Log.d("converted result", json);
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject("{" + json +"}");
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

LogCat信息

01-29 11:45:53.556: D/Search keyword:(921): saint louis
01-29 11:45:57.288: D/converted result(921): 
connected{"products":[{"pid":"406355","name":"852610 SOUTHCOUNTYMALL"},{"pid":"406356","name":"852611 SOUTHCOUNTYMALL"},{"pid":"406357","name":"852612 SOUTHCOUNTYMALL"}],"success":1}

01-29 11:45:57.288: E/JSON Parser(921): Error parsing data org.json.JSONException: Expected ':' after connected at character 11 of {connected{"products":[{"pid":"406355","name":"852610 SOUTHCOUNTYMALL"},{"pid":"406356","name":"852611 SOUTHCOUNTYMALL"},{"pid":"406357","name":"852612 SOUTHCOUNTYMALL"}],"success":1}
01-29 11:45:57.288: E/JSON Parser(921): }

2 个答案:

答案 0 :(得分:4)

由于错误明确指出,您的JSON无效,因为它前面有单词connected

您需要让服务器停止发送该字词。

答案 1 :(得分:1)

你有这个JSON:

{connected{"products":[{"pid":"406355","name":"852610 SOUTHCOUNTYMALL"},{"pid":"406356","name":"852611 SOUTHCOUNTYMALL"},{"pid":"406357","name":"852612 SOUTHCOUNTYMALL"}],"success":1}

这是一种无效的JSON格式,因为您在JSON的开头有错误的表达式“{connected”。也许,你应该得到这样的JSON:

{"products":[{"pid":"406355","name":"852610 SOUTHCOUNTYMALL"},{"pid":"406356","name":"852611 SOUTHCOUNTYMALL"},{"pid":"406357","name":"852612 SOUTHCOUNTYMALL"}],"success":1}

或者像这样:

{"connected":[VALUE], "products":[{"pid":"406355","name":"852610 SOUTHCOUNTYMALL"},{"pid":"406356","name":"852611 SOUTHCOUNTYMALL"},{"pid":"406357","name":"852612 SOUTHCOUNTYMALL"}],"success":1}

无论如何,我建议你使用Gson库来构建和获取JSON。