0

我有这样的 JSON:

{
  "shops": [
    {
          "id": "831",
          "name": "18 and East",
          "categories": [
            "1",
            "12",
            "13"
          ],
          "locations": [
            {
              "lat": "53.403297",
              "lng": "-2.978689",
              "address": "Bold Street Liverpoool, L1 4EA"
            },
            {
              "lat": "51.590111",
              "lng": "-0.146134",
              "address": "58 Fortis Green Road, London, N10 3HN"
            },
            {
              "lat": "53.406738",
              "lng": "-2.981188",
              "address": "137-139 Market Square  Liverpool"
            }
          ],
          "image": "5574-18-and-East-sale.jpg"
        }
    ....

我有 Shop.java、Response.java 和 Locations.java 像这样(这个文件将数据作为对象获取):

现在我想将地址解析为以下文件,我尝试了几种方法,但我无法解析数组中的地址。而且我能够解析 id、name 和 image。

有人可以帮我解决这个问题吗?

4

1 回答 1

0

我附上我的代码:

添加您的班级 Location.class、Shop.class 和 Response.class - 没有变化

//Code which parse json put it in your "doInBackground"
try {
        String str = getString(R.string.data);
        Gson gson = new Gson();
        Response response = gson.fromJson(str, Response.class);

        if(response != null){
           //TODO response is not null
           Log.e("", "ADDRESS: " + response.shops.get(0).getLocations().get(0).address);
        }

} catch (Exception e){
    e.printStackTrace();
}

//在strings.xml中我添加了我解析的json字符串

<string name="data">
    {
    \"shops\": [
    {
    \"id\": \"831\",
    \"name\": \"18 and East\",
    \"categories\": [
    \"1\",
    \"12\",
    \"13\"
    ],
    \"locations\": [
    {
    \"lat\": \"53.403297\",
    \"lng\": \"-2.978689\",
    \"address\": \"Bold Street Liverpoool, L1 4EA\"
    },
    {
    \"lat\": \"51.590111\",
    \"lng\": \"-0.146134\",
    \"address\": \"58 Fortis Green Road, London, N10 3HN\"
    },
    {
    \"lat\": \"53.406738\",
    \"lng\": \"-2.981188\",
    \"address\": \"137-139 Market Square  Liverpool\"
    }
    ],
    \"image\": \"5574-18-and-East-sale.jpg\"
    }]}

</string>

解析响应后存在解析的“地址”,请检查:)

我的日志:09-11 20:16:17.765: D/(2610): 地址: Bold Street Liverpoool, L1 4EA

============= 更新将此功能添加到商店类中:

public ArrayList<String> getShopAddress(){
   ArrayList<String> shoopAddress = new ArrayList<String>();
   if(locations == null){
     //there is no address
     return shoopAddress;
   }

   for(Locations l : locations){
      final String addr = l. getAddress();
      if(addr != null)
        shoopAddress.add(addr);
    }
   return shoopAddress;
}

现在您可以通过以下方式获取商店中的所有地址:

response.shops.get(0).getShopAddress(); //and it returns all address (as strings list) assigned to shop
于 2013-09-11T18:14:19.427 回答