org.json.JSONException:JSONObject文本必须以' {'在角色1

时间:2015-10-16 13:18:15

标签: java json

我尝试搜索此错误。 Google搜索结果有很多结果,但对我来说没什么用。 这是我的网络服务方法

@GET
@Path("/values")
public String test() {

    return "{\"x\":5,\"y\":6}";

}

这是我的客户代码

public class Check {
public static void main(String[] args){
    String url = "http://localhost:8181/math/webapi/values";
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(request);
        String value = response.toString();
        JSONObject json = new JSONObject(value);
        int i = json.getInt("x");
        System.out.println(i);
    }catch (Exception e) {
        e.printStackTrace();
    }       
}

以上代码是初学者代码,用于学习如何使用它。如果这个问题得到解决,我必须将知识应用到另一个应用程序中。客户端代码,我想在android中使用逻辑。

修改

public class Check {
public static void main(String[] args){
    String url = "http://localhost:8181/math/webapi/values";
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(request);
        InputStream value = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(value));
        String jsonValue = br.readLine();
        JSONObject json = new JSONObject(jsonValue);
        int i = json.getInt("x");
        System.out.println(i);
    }catch (Exception e) {
        e.printStackTrace();
    }       
}

2 个答案:

答案 0 :(得分:3)

相当确定response.toString不会按照您的想法行事,因为它不是listed in the documentation

我认为您需要使用response.getEntity,然后使用entity.getContent,它会为您提供InputStream来阅读内容。然后将该流传递给您的解析器。

答案 1 :(得分:1)

试试这段代码。如上所述使用IOUtils。它会起作用。

public class Check {
public static void main(String[] args){
String url = "http://localhost:8181/math/webapi/values";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
    HttpResponse response = httpClient.execute(request);
    InputStream value = response.getEntity().getContent();
    String jsonValue = IOUtils.toString(value);
    JSONObject json = new JSONObject(jsonValue);
    int i = json.getInt("x");
    System.out.println(i);
}catch (Exception e) {
    e.printStackTrace();
}       
}
相关问题