gpt4 book ai didi

java - Json 中的特殊字符

转载 作者:行者123 更新时间:2023-12-01 18:27:51 26 4
gpt4 key购买 nike

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

        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

最后一行异常(exception):

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

结果字符串是:

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

如何防止此异常?

最佳答案

and the result String is : {\r\n \"xUserPW\": \"dStT0T\"\r\n}

这不是有效的 json 格式。 Web服务是否返回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());

不应出现错误

关于java - Json 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25389301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com