Android

Android JSON解析(1) 陣列包物件 物件包陣列 陣列包物件

練習:https://reurl.cc/KxjQmj

1.先把第一層解析出來

CityModel

import java.util.List;

public class CityModel {
    private String CityName;
    private String CityEngName;
    private List<AreaModel> AreaList;

    public CityModel() {
    }

    public CityModel(String cityName, String cityEngName, List<AreaModel> areaList) {
        CityName = cityName;
        CityEngName = cityEngName;
        AreaList = areaList;
    }

    public String getCityName() {
        return CityName;
    }

    public void setCityName(String cityName) {
        CityName = cityName;
    }

    public String getCityEngName() {
        return CityEngName;
    }

    public void setCityEngName(String cityEngName) {
        CityEngName = cityEngName;
    }

    public List<AreaModel> getAreaList() {
        return AreaList;
    }

    public void setAreaList(List<AreaModel> areaList) {
        AreaList = areaList;
    }
}

2.再把第二層陣列也解析出來

AreaModel

public class AreaModel {
    private String ZipCode;
    private String AreaName;
    private String AreaEngName;

    public AreaModel() {
    }

    public AreaModel(String zipCode, String areaName, String areaEngName) {
        ZipCode = zipCode;
        AreaName = areaName;
        AreaEngName = areaEngName;
    }

    public String getZipCode() {
        return ZipCode;
    }

    public void setZipCode(String zipCode) {
        ZipCode = zipCode;
    }

    public String getAreaName() {
        return AreaName;
    }

    public void setAreaName(String areaName) {
        AreaName = areaName;
    }

    public String getAreaEngName() {
        return AreaEngName;
    }

    public void setAreaEngName(String areaEngName) {
        AreaEngName = areaEngName;
    }
}

3.用Okhttp去讀取資料

Request request = new Request.Builder()
         .url("https://api.myjson.com/bins/130mpi")
         .build();

 new OkHttpClient().newCall(request).enqueue(new okhttp3.Callback() {
     @Override
     public void onFailure(okhttp3.Call call, IOException e) {

     }

     @Override
     public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
         String json = response.body().string();
         Gson gson = new Gson();
         List<CityModel> cityModel = gson.fromJson(json, new TypeToken<List<CityModel>>() {
            }.getType());

            for (CityModel model : cityModel) {
                //取得縣市
                String cityName = model.getCityName();
                for (AreaModel areaModel : model.getAreaList()) {
                    //取得區域
                    String areaName = areaModel.getAreaName();
                    //合成縣市與區域
                    String cityData = cityName + areaName;
                    cities.add(cityData);
                }
            }
        }
    });

發表迴響