如何使用Gson解析这个Json

时间:2011-11-25 05:15:47

标签: android json gson

如何使用Gson解析此Json并显示Placetype _Name和Place details?

我有这个json,需要帮助解析并显示Placetype _Name和Place详细信息。

{
  "PlacesList": {
"PlaceType": [
  {
    "-Name": "Airport",
    "Places": {
      "Place": [
        {
          "name": "Juhu Aerodrome",
          "latitude": "19.09778",
          "longitude": "72.83083",
          "description": "Juhu Aerodrome is an airport that serves the metropolitan" 
        },
        {
          "name": "Chhatrapati Shivaji International Airport",
          "latitude": "19.09353",
          "longitude": "72.85489",
          "description": "Chhatrapati Shivaji International Airport  "
        }
      ]
    }
  },
  {
    "-Name": "Mall",
    "Places": {
      "Place": [
        {
          "name": "Infinity",
          "latitude": "19.14030",
          "longitude": "72.83180",
          "description": "This Mall is one of the best places for all types of brand"
        },
        {
          "name": "Heera Panna",
          "latitude": "18.98283",
          "longitude": "72.80897",
          "description": "The Heera Panna Shopping Center is one of the most popular"
        }
      ]
    }
  }
]
  }
} 

1 个答案:

答案 0 :(得分:5)

处理以“ - ”开头的JSON元素名称的简单解决方案是使用@SerializedName注释,这是一个不能用于启动Java标识符名称的字符。

import java.io.FileReader;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public class GsonFoo
{
  public static void main(String[] args) throws Exception
  {
    Response response = new Gson().fromJson(new FileReader("input.json"), Response.class);
    System.out.println(response.PlacesList.PlaceType.get(0).Name);
    System.out.println(response.PlacesList.PlaceType.get(0).Places.Place.get(0).name);
    System.out.println(response.PlacesList.PlaceType.get(0).Places.Place.get(0).description);
  }
}

class Response
{
  PlacesList PlacesList;
}

class PlacesList
{
  List<PlaceType> PlaceType;
}

class PlaceType
{
  @SerializedName("-Name")
  String Name;
  Places Places;
}

class Places
{
  List<Place> Place;
}

class Place
{
  String name;
  String latitude;
  String longitude;
  String description;
}

输出:

Airport
Juhu Aerodrome
Juhu Aerodrome is an airport that serves the metropolitan