Android 中的 JSONArray 到 ArrayList

JSONArray to ArrayList in Android

我从服务器“dataArray”得到如下的 jsonarray:

[{"FirstNmae":"xyz","BranchId":"asd","Location":"qwe"}]

现在我想使用 Gson 创建 ArrayList<EmpData> 列表,其中 EmpData 是普通的 Pojo class。下面是我的代码,它出错了

TypeToken<List<EmpData>> token = new TypeToken<List<EmpData>>() {};
List<EmpData> empList = gson.fromJson(dataArray, token.getType());

不是答案,但包含为显示格式化代码的答案。

无法重现。这是一个 Minimal, Reproducible Example,根据问题中的信息,它运行良好。

为简单起见,代码使用 public 字段。实际代码可能会使用私有字段和 getter/setter 方法,但由于 POJO 不是问题,所以我保持简单。

Gson gson = new Gson();

// Code from question starts here

String dataArray = "[{\"FirstNmae\":\"xyz\",\"BranchId\":\"asd\",\"Location\":\"qwe\"}]";

TypeToken<List<EmpData>> token = new TypeToken<List<EmpData>>() {};
List<EmpData> empList = gson.fromJson(dataArray, token.getType());

// Code from question ends here

System.out.println("dataArray = " + dataArray);
System.out.println("empList = " + empList);
class EmpData {
    @SerializedName("FirstNmae")
    public String firstName;
    @SerializedName("BranchId")
    public String branchId;
    @SerializedName("Location")
    public String location;
    @Override
    public String toString() {
        return "EmpData[firstName=" + this.firstName +
                     ", branchId=" + this.branchId +
                     ", location=" + this.location + "]";
    }
}

输出

dataArray = [{"FirstNmae":"xyz","BranchId":"asd","Location":"qwe"}]
empList = [EmpData[firstName=xyz, branchId=asd, location=qwe]]

请注意 @SerializedName 注释如何用于处理名称中的拼写错误 (FirstNmae),以及名称中第一个字母的 uppercase/lowercase 问题。