当前位置: 首页 > 知识库问答 >
问题:

应为BEGIN_OBJECT,但BEGIN_ARRAY位于第1行第2列路径$

燕正卿
2023-03-14
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Gson gson = new GsonBuilder().create();
PayoutCharges payoutList = gson.fromJson(reader, PayoutCharges.class);
package com.app.driver.entity;

import java.util.ArrayList;

import com.google.gson.annotations.SerializedName;

public class PayoutCharges {
    //handle error
    @SerializedName("error")
    private Error mError;

    public Error getError() {
        return mError;
    }

    public void setError(Error error) {
        mError = error;
    }

    //handle data
    @SerializedName("payoutCharges")
    private ArrayList<PayoutCharge> mPayoutCharges;

    public ArrayList<PayoutCharge> getPayoutCharges() {
        return mPayoutCharges;
    }

    public void setPayoutCharges(ArrayList<PayoutCharge> payoutCharges) {
        mPayoutCharges = payoutCharges;
    }
}

在阅读@Ridcully的响应之后,我想问一下是否有一种方法可以更新payoutcharges.java,以便它知道JSON是一个数组。比如@serializedname([])

共有1个答案

章光华
2023-03-14

下面的代码适用于示例json值:

String val1 = "[{test: \"test\"}]";

final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();

TestCase[] testCase = gson.fromJson(val1, TestCase[].class);

TestCase holder类:

private static class TestCase {
    @SerializedName("test")
    private String field;
}

您共享的测试示例有一个包含对象的数组。因此,在将json值反序列化为对象(数组)时,必须使用pojo类的数组。

 类似资料: