我有一個安靜的端點,它在端點http://127.0.0.1:4567/suppliers
上執行GET時提供下面的JSON。使用gson解析json數組中的對象
{
"status": "SUCCESS",
"jsonapi": {
"version": "1.0"
},
"data": {
"id": 0,
"type": "suppliers",
"name": "Red Network Energy LTD"
}
}
在我使用GSON上述數據解析到SupplierResponseTest
對象httpPost請求。當執行:
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;
}
}
您需要爲您創建自定義'JsonDeserializer'Json字符串,此鏈接可能有所幫助(http://www.programcreek.com/java-api-examples/index.php?api=com.google.gson。 JsonDeserializer)在你Json的'數據'是一個數組,但在你的課'ResponseDataTest數據'是一個對象在JSON條款 –
我試圖將所有對'數據'的引用轉換爲數組,但然後我得到一個相同的錯誤 – TheMightyLlama