我在解析 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
尝试在字符串的对象数组中创建"文本"字段:
String[] text
你的响应有数组,你尝试将其解析为 String 对象:
{"code": 200, "lang": "en-ru", "text": ["жизнь"]}
另请参阅此处解析数组的示例。