使用 Gson 2.3.1 解析 Json 文件

Parsing a Json file with Gson 2.3.1

有这个 json 文件要用 GSON 库解析

{"type": "FeatureCollection","features": [{"type":"Feature","properties":{"qualityScore":72,"formattedAddress":"Rue du Commerce; 4100 Seraing; Belgium","address":"rue du commerce","name":"rue du commerce"},"geometry":{"type":"Point","coordinates":[5.50852,50.612572]}},{"type":"Feature","properties":{"qualityScore":72,"formattedAddress":"Rue du Commerce; 4219 Meeffe; Belgium","address":"rue du commerce","name":"rue du commerce"},"geometry":{"type":"Point","coordinates":[5.01752,50.606201]}},{}]}

所以这是我创建的用于从 Json 文件

填充它的 bean
import java.util.List;
import com.google.gson.annotations.Expose;

public class Address {

    @Expose
    private String type;

    @Expose
    private List<GeolocationFeature> features = new ArrayList<GeolocationFeature>();

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<GeolocationFeature> getFeatures() {
        return features;
    }

    public void setFeatures(List<GeolocationFeature> features) {
        this.features = features;
    }

    @Override
    public String toString() {
        return "Address [type=" + type + ", features=" + features
                + "]";
    }
}

然后当我尝试用 Gson 解析它时:

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Type listType = new TypeToken<List<Address>>() {}.getType();
gson.fromJson(jsonString, listType);

我遇到了这个奇怪的错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

问题是您正在尝试将 JSON 对象解析为列表。

列表由您收到的 JSON 对象中的 "features" 属性 表示。您可以创建一个包装器 class,其结构与您的 JSON 响应相同,然后使用 GSON 对其进行解析。

public class AddressWrapper {

    private String type;
    private List<Address> addresses;

    // getters and setters, etc...
}

然后就可以用GSON解析了:

AddressWrapper addressWrapper = gson.fromJson(jsonString, AddressWrapper.class);

并访问地址:

List<Address> addresses = addressWrapper.getAddresses();

或者,您也可以创建自定义解析逻辑,并使用它来提取主 JSON 对象的 "features" 属性 的内容,并将其解析为列表.您可以查阅有关反序列化器的 GSON 文档来执行此操作。

我有:

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
gson.fromJson(jsonString, Address.class);