Krishna
Krishna

Reputation: 621

org.json.JSONException: A JSONObject text must begin with '{' at character 1

I tried searching for this error. There are many results on google for this search but nothing proved useful to me. This is my web service method

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

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

}

This is my client code

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();
    }       
}

The above code is a starter code and it is for learning how to use it. If this is solved, I have to apply the knowledge in another application. The client side code, I want to use the logic in android.

EDIT

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();
    }       
}

Upvotes: 0

Views: 2304

Answers (2)

Venkata
Venkata

Reputation: 135

Try this code. Use IOUtils as mentioned. it will work.

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();
}       
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074676

Fairly certain response.toString doesn't do what you think it does, as it's not listed in the documentation.

I believe you need to use response.getEntity, and then entity.getContent, which gives you an InputStream to read the content from. Then pass that stream into your parser.

Upvotes: 3

Related Questions