Json中的特殊人物

时间:2014-08-19 17:15:59

标签: java android json

我使用了一个我没有足够控制权的web服务,所以我必须解析它返回的内容!这是解析部分:

        HttpResponse getResponse =  httpclient.execute(httpPost);  
        HttpEntity returnEntity = getResponse.getEntity();
        is = returnEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 128);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        String result = sb.toString();
        result = result.replaceAll("^\"(.*)\"$","$1");
        JSONObject jObject = new JSONObject(result); //this line throws error

最后一行例外:

org.json.JSONException: Expected literal value at character 1 of {\r\n  \"xUserPW\": \"EmU7cU\"\r\n}

,结果字符串为:

{\r\n  \"xUserPW\": \"EmU7cU\"\r\n}

我该如何防止此异常?

3 个答案:

答案 0 :(得分:2)

  

,结果字符串为:{\ r \ n \“xUserPW \”:\“dStT0T \”\ r \ n}

这不是有效的json格式。 webservice是否会让你回到json?您不能简单地将\ n附加到收到的数据并进行转换。

HttpResponse getResponse =  httpclient.execute(httpPost);  
    HttpEntity returnEntity = getResponse.getEntity();
    is = returnEntity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 128);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line);
    }
    JSONObject jObject = new JSONObject(sb.toString());

不应该错误

答案 1 :(得分:1)

JSONException: Expected literal value at character表示返回的.json必须无效!

这是一种无效的.json格式:

{\r\n \"xUserPW\": \"dStT0T\"\r\n}

答案 2 :(得分:1)

让我们看一下json.org:http://json.org/

在该网站中,侧边菜单中定义的json只是沿着与您的问题相关的路径:

object -> { members }    // each object replaces by { members }
members  -> pair      // each  members  replaces by pair
pair ->  string : value  // and so on ...
string -> "chars"
" chars " -> char chars
char -> any-Unicode-character-
        except-"-or-\-or-
        control-character  \"  \\  \/  \b \f \n \r \t \u four-hex-digits 

所以你的json不能以控制字符开头,但是我检查了它,而在其他json验证器中它可以在例如: http://www.freeformatter.com/json-validator.html 但在json.org,它不是。所以只需从开始和结束时删除\r\n