【发布时间】:2017-07-12 07:13:15
【问题描述】:
我有一个 restful 端点,它在端点 http://127.0.0.1:4567/suppliers 上执行 GET 时提供以下 JSON。
{
"status": "SUCCESS",
"jsonapi": {
"version": "1.0"
},
"data": {
"id": 0,
"type": "suppliers",
"name": "Red Network Energy LTD"
}
}
在 httpPost 请求中,我使用 GSON 将上述数据解析为 SupplierResponseTest 对象。执行时:
SupplierResponseTest supplierResponse = gson.fromJson(supplierJsonResponse, SupplierResponseTest.class);
我得到错误:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 57 path $.data
public SupplierResponseTest sendPostRequest(String supplierName){
SupplierResponseTest supplierResponse;
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
//Create new object
SupplierTest supplier = new SupplierTest(supplierName);
//convert to Json
Gson gson = new Gson();
String requestBody = gson.toJson(supplier);
//set entity
HttpPost request = new HttpPost("http://127.0.0.1:4567/suppliers");
StringEntity params = new StringEntity(requestBody);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String supplierJsonResponse = EntityUtils.toString(result.getEntity(), "UTF-8");
supplierResponse = gson.fromJson(supplierJsonResponse, SupplierResponseTest.class);
return supplierResponse;
} catch (Exception e) {
String status = "";
System.out.println(e.getMessage());
System.out.println(e.getClass());
System.out.println(e.getStackTrace());
status = "NOK";
}
//return status;
return null;
}
对象如下。
package json.responses;
import com.google.gson.Gson;
public class SupplierResponseTest {
private StatusResponseTest status;
private ApiVersionResponseTest jsonapi;
private String message;
private ResponseDataTest data;
public SupplierResponseTest(StatusResponseTest status, ApiVersionResponseTest jsonapi) {
this.status = status;
this.jsonapi = jsonapi;
}
public SupplierResponseTest(StatusResponseTest status, ApiVersionResponseTest jsonapi, String data, String message) {
this.status = status;
this.jsonapi = jsonapi;
this.message = message;
//data which needs to take into account the array of suppliers
try{
Gson gson = new Gson();
this.data = gson.fromJson(data, ResponseDataTest.class);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public StatusResponseTest getStatus() {
return status;
}
public ApiVersionResponseTest getJsonapi() {
return jsonapi;
}
public String getMessage() {
return message;
}
//getData which needs to take into account the array of suppliers
public ResponseDataTest getData() {
return data;
}
}
【问题讨论】:
-
您需要为您的 Json 字符串创建自定义的“JsonDeserializer”,此链接可能会有所帮助 (programcreek.com/java-api-examples/…) 在您中,Json 的“数据”是一个数组,但在您的类中,“ResponseDataTest 数据”是一个JSON 术语中的对象
-
我尝试将所有对
data的引用转换为一个数组,但是我得到了同样的错误