gpt4 book ai didi

java - 使用 GSON 给出错误预期 BEGIN_ARRAY 但为 STRING

转载 作者:搜寻专家 更新时间:2023-11-01 07:36:37 24 4
gpt4 key购买 nike

示例 JSON 对象如下所示:

[{"Title":"John Doe","Address":{"AddressLines":["The Place","123 New Place","London","England"],"Postcode":"NW7 XXY"},"Telephone":"0012345","Email":"","Latitude":51.5024472101345,"Longitude":-0.557585646554,"Easting":500623,"Northing":179647}]

假设通过链接 www.domain.com 访问上述对象,我有以下类来表示数据

public class LocationData extends Data{

private Address Address;
private String Telephone;
private String Email;
private String Latitude;
private String Longitude;
private String Easting;
private String Northing;

public Address getAddress() {
return Address;
}

public void setAddress(Address address) {
Address = address;
}

public String getTelephone() {
return Telephone;
}

public void setTelephone(String telephone) {
Telephone = telephone;
}

public String getEmail() {
return Email;
}

public void setEmail(String email) {
Email = email;
}

public String getLatitude() {
return Latitude;
}

public void setLatitude(String latitude) {
Latitude = latitude;
}

public String getLongitude() {
return Longitude;
}

public void setLongitude(String longitude) {
Longitude = longitude;
}

public String getEasting() {
return Easting;
}

public void setEasting(String easting) {
Easting = easting;
}

public String getNorthing() {
return Northing;
}

public void setNorthing(String northing) {
Northing = northing;
}

}

地址类如下:

public class Address {

public String[] AddressLines;

public String Postcode;

public String getPostcode() {
return Postcode;
}

public void setPostcode(String postcode) {
Postcode = postcode;
}

public String[] getAddressLines() {
return AddressLines;
}

public void setAddressLines(String addressLines[]) {
AddressLines = addressLines;
}


}

当我尝试运行时

LocationData[] data = gson.fromJson(this.locationServiceUrl, LocationData[].class);
return data;

我收到以下错误:

应为 BEGIN_ARRAY,但在上述代码行中为字符串。我不确定我设置类(class)的方式是否有问题。注意:我使用的是数组(LocationData[] 数据),因为该服务返回多个位置,尽管我在上面显示的示例中只包含了一个位置。非常感谢任何关于为什么会发生这种情况的帮助。我已经查看了此处的一些类似错误,但所提供的修复似乎都不适合我。

最佳答案

{
"finally":[
{
"Title":"John Doe",
"Address": {
"AddressLines":[
"The Place",
"123 New Place",
"London",
"England"
],
"Postcode":"NW7XXY"
},
"Telephone":"0012345",
"Email":"",
"Latitude":51.5024472101345,
"Longitude":-0.557585646554,
"Easting":500623,
"Northing":179647
}
]
}

解析这个 JSON 的代码是:

public class mainData {

public List<LocationData> finally;

public String[] getLocationData() {
return AddressLines;
}

public void setLocationData(List<LocationData> finally) {
this.finally = finally;
}
}

是因为你的字符串以[开头当你用 Gson 解析这种类型的 Json 时,你需要为它添加一个标签前缀,就像我所做的那样 ( {"finally": your data } )。

实际上 Gson 试图映射标签及其值,但在您的情况下是 [不包含 Gson 可以映射的标签。

关于java - 使用 GSON 给出错误预期 BEGIN_ARRAY 但为 STRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com