我有一个关于将字符串解析为java对象的问题。我有这个回应:
{
"status": "success",
"paginated": false,
"data": [{
"user": {
"id": 21,
"email": "[email protected]",
"access_token": "ai_wy-tTLLEyRCPAF86dWPJdQ77gefsTPwBkvtlEkNs",
"test": []
}
}],
"message": ""
}
并且我想获得状态
我创建了此类并仅设置状态,因为这是我想要的唯一字段,其余所有响应都不重要
package responseObjects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
public class LogInResponse {
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonProperty("status")
public String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
在程序中,我发送请求并获得响应,但是当我尝试将其设置为java对象时,它失败了诠释这行LogInResponse res = gson.fromJson(response.body().toString(),LogInResponse.class);
public class TestMain {
OkHttpClient client = new OkHttpClient();
JsonObject bodyJson = new JsonObject();
JsonObject responseJson = new JsonObject();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public String httpPost(String url, String json) throws IOException {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
String strResponse = response.body().string();
JsonObject jsonObjectResponse = new JsonParser().parse(strResponse).getAsJsonObject();
Gson gson = new Gson();
LogInResponse res = gson.fromJson(response.body().toString(),LogInResponse.class);
return response.body().string();
}
这是例外
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)
有人可以告诉我哪里出了问题吗?如何从响应中获取状态?问候
response.body().string()
获取JSON字符串,但在失败的行中,您编写了response.body().toString()
,这是另一种方法。body()
的文档如果此响应传递到Callback.onResponse或从Call.execute返回,则返回非null值。也就是说,您使用了两次。您已经在响应主体必须关闭,并且只能使用一次。
body()
中拥有了它。继续使用那个。