0

I'm having trouble parsing the JSON response for the http post request. What is the issue regarding Json parsing here?

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost("url");

    post.addHeader("Content-Type", "application/json");
    HttpResponse response = client.execute(post);

    System.out.println(response.getStatusLine());

    JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent()));
    Gson gson = new Gson();
    textConv text = gson.fromJson(reader.toString(), textConv.class);
    System.out.println(text.text);

OUTPUT

HTTP/1.1 200 OK
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)
    at com.google.gson.Gson.fromJson(Gson.java:813)
    at gsonTest.main(gsonTest.java:44)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215)
    ... 5 more
Cœur
  • 37,241
  • 25
  • 195
  • 267
root
  • 157
  • 1
  • 3
  • 16

1 Answers1

1

Try making your 'text' field in the object array of strings:

String[] text

Your response has array, and you try to parse it into String object:

{"code": 200, "lang": "en-ru", "text": ["жизнь"]}

Look also here for example of parsing arrays.

khusrav
  • 5,267
  • 5
  • 27
  • 38