解析JSON respose

时间:2018-06-17 20:27:06

标签: java json translators

我在解析http post请求的JSON响应时遇到问题。我已经经历了很多关于Json解析的问题,但是还没有能够找出问题所在。你能帮帮我吗? 谢谢

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

输出

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

1 个答案:

答案 0 :(得分:1)

尝试在字符串的对象数组中创建'text'字段:

String[] text

您的响应有数组,并尝试将其解析为String对象:

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

另请参阅here,例如解析数组。