本文介绍了使用gson解析json数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个安静的端点,它在端点 http://127.0.0.1:4567/suppliers 上执行GET时提供了下面的JSON。

  {
status:SUCCESS,
jsonapi:{
version:1.0
},
data:{
id:0,
type:suppliers,
name :红网络能源有限公司
}
}

在httpPost请求我使用GSON将上述数据解析到 SupplierResponseTest 对象中。执行时:

SupplierResponseTest supplierResponse = gson.fromJson(supplierJsonResponse,SupplierResponseTest.class);



我得到错误:

java.lang.IllegalStateException:预期的BEGIN_OBJECT,但在第1行是BEGIN_ARRAY列57路径$ .data

  public SupplierResponseTest sendPostRequest(String supplierName){


SupplierResponseTest supplierResponse;


尝试(CloseableHttpClient httpClient = HttpClientBuilder.create()。build()){


//创建新对象
SupplierTest supplier = new SupplierTest(supplierName);

//转换为Json
Gson gson = new Gson();
字符串requestBody = gson.toJson(supplier);


//设置实体

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);

返回supplierResponse;







$ b} catch(例外e){
字符串状态= ;
System.out.println(e.getMessage());
System.out.println(e.getClass());
System.out.println(e.getStackTrace());

status =NOK;

}
//返回状态;
返回null;


对象如下。

  package json.responses; 
import com.google.gson.Gson;

公共类SupplierResponseTest {

私有StatusResponseTest状态;
private ApiVersionResponseTest jsonapi;
私人字符串消息;
私有ResponseDataTest数据;


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

$ b public SupplierResponseTest(StatusResponseTest status,ApiVersionResponseTest jsonapi,String data,String message){
this.status = status;
this.jsonapi = jsonapi;
this.message = message;

//需要考虑供应商数组的数据
try {
Gson gson = new Gson();
this.data = gson.fromJson(data,ResponseDataTest.class);

$ b $ catch(Exception e){
System.out.println(e.getMessage());
}
}

public StatusResponseTest getStatus(){
return status;
}
public ApiVersionResponseTest getJsonapi(){
return jsonapi;
}
public String getMessage(){
return message;
}

// getData需要考虑供应商数组
public ResponseDataTest getData(){
return data;
}

}


解决方案

在你的类中 SupplierResponseTest.java


$ b 替换 private ResponseDataTest data; / code> with private ResponseDataTest [] data;



并替换 private StatusResponseTest状态; 私人字符串状态;



'包含JSONArray



查看此代码 -

  package com。 stack.example; 

import com.google.gson.Gson;

公共类SupplierResponseTest {

私有字符串状态;
private ApiVersionResponseTest jsonapi;
私人字符串消息;
private ResponseDataTest [] data;


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

$ b public SupplierResponseTest(String status,ApiVersionResponseTest jsonapi,String data,String message){
this.status = status;
this.jsonapi = jsonapi;
this.message = message;

//需要考虑供应商数组的数据
try {
Gson gson = new Gson();
this.data = gson.fromJson(data,ResponseDataTest []。class);

$ b $ catch(Exception e){
System.out.println(e.getMessage());
}
}

public String getStatus(){
return status;
}
public ApiVersionResponseTest getJsonapi(){
return jsonapi;
}
public String getMessage(){
return message;
}

// getData需要考虑供应商数组
public ResponseDataTest [] getData(){
return data;
}

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

public class ApiVersionResponseTest {

private String version;

public ApiVersionResponseTest(){
super();
// TODO自动生成的构造函数存根

$ b $ 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;
私有字符串类型;
私人字符串名称;
public ResponseDataTest(){
super();
// TODO自动生成的构造函数存根

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能源有限公司},
+{\id \:72,\type\:\suppliers \,\name \:\\ \\Orange Network Energy LTD \},
+{\id \:73,\type\:\suppliers \,\name \\ \\:绿色网络能源有限公司\\}}};

Gson gson = new Gson();

//将json解析为SupplierResponseTest对象。
SupplierResponseTest supplierResponse = gson.fromJson(jsonResponse,SupplierResponseTest.class);

System.out.println(supplierResponse);

}

}

为你工作。


I have a restful endpoint which provides the below JSON when performing a GET on the endpoint http://127.0.0.1:4567/suppliers.

    {
    "status": "SUCCESS",
    "jsonapi": {
        "version": "1.0"
    },
    "data": {
        "id": 0,
        "type": "suppliers",
        "name": "Red Network Energy LTD"
    }
}

In the httpPost request I use GSON to parse the above data into the SupplierResponseTest object. When executing:

SupplierResponseTest supplierResponse = gson.fromJson(supplierJsonResponse, SupplierResponseTest.class);

I get the error:

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;

}

The Object is as below.

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;
    }

}
解决方案

In your class - SupplierResponseTest.java

Replace private ResponseDataTest data; with private ResponseDataTest[] data;

and replace private StatusResponseTest status; with private String status;

As in your JSON response 'data' contains JSONArray

Look at this code -

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);

    }

}

Hope this will work for you.

这篇关于使用gson解析json数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 11:51