【问题标题】:Parsing objects in a json array with gson使用 gson 解析 json 数组中的对象
【发布时间】: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 的引用转换为一个数组,但是我得到了同样的错误

标签: java json gson


【解决方案1】:

在你的课堂上 - SupplierResponseTest.java

private ResponseDataTest data; 替换为private ResponseDataTest[] data;

并将private StatusResponseTest status; 替换为private String status;

在您的 JSON 响应中,“数据”包含 JSONArray

看看这段代码-

package com.stack.example;

import com.google.gson.Gson;

public class SupplierResponseTest {

    private String status;
    private ApiVersionResponseTest jsonapi;
    private String message;
    private ResponseDataTest[] data;


    public SupplierResponseTest(String status, ApiVersionResponseTest jsonapi) {
        this.status = status;
        this.jsonapi = jsonapi;

    }
    public SupplierResponseTest(String 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 String 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;
    }

    @Override
    public String toString() {
        return "SupplierResponseTest [status=" + status + ", jsonapi="
            + jsonapi + ", message=" + message + ", data=" + data + "]";
    }
}

public class ApiVersionResponseTest {

    private String version;

    public ApiVersionResponseTest() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ApiVersionResponseTest(String version) {
        super();
        this.version = version;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }   
}

package com.stack.example;

public class ResponseDataTest {

    private int id;
    private String type;
    private String name;
    public ResponseDataTest() {
        super();
        // TODO Auto-generated constructor stub
    }
    public ResponseDataTest(int id, String type, String name) {
        super();
        this.id = id;
        this.type = type;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

package com.stack.example;

import com.google.gson.Gson;

public class Stack {


    public static void main(String[] args) {

        String jsonResponse = "{\"status\": \"SUCCESS\",\"jsonapi\": {\"version\": \"1.0\"},\"data\": ["
                + "{\"id\": 70,\"type\": \"suppliers\",\"name\": \"Blue Network Energy LTD\"},"
                + "{\"id\": 71,\"type\": \"suppliers\",\"name\": \"Red Network Energy LTD\"},"
                + "{\"id\": 72,\"type\": \"suppliers\",\"name\": \"Orange Network Energy LTD\"},"
                + "{\"id\": 73,\"type\": \"suppliers\",\"name\": \"Green Network Energy LTD\"}]}";

        Gson gson = new Gson();

        //Parse json into a SupplierResponseTest object.
        SupplierResponseTest supplierResponse = gson.fromJson(jsonResponse, SupplierResponseTest.class);

        System.out.println(supplierResponse);

    }

}

希望这对你有用。

【讨论】:

  • @TheMightyLlama 我认为您遗漏了一些东西,看看我在答案中添加的代码,它工作正常。
  • 你说得对,这很有效。我在json中犯了一个错误。问题已修改。问题在于解析 POST 的响应,其 json 响应包括供应商 data 作为元素而不是数组。
  • @TheMightyLlama 在这种情况下将SupplierResponseTest.java 中的StatusResponseTest 的数据类型更改为String
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2013-08-27
相关资源
最近更新 更多