使用GSON将JSON解析为对象

时间:2013-09-11 16:31:44

标签: android json android-asynctask gson android-gridview

我的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,名称和图像。

有人能帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分: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):ADDRESS: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