2011-11-25 213 views
-2

如何使用Gson解析此Json並顯示Placetype _Name和Place詳細信息?如何使用Gson解析此Json

我有這個JSON,需要幫助解析和顯示Placetype _Name和地方的詳細信息。

{ 
    "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" 
     } 
     ] 
    } 
    } 
] 
    } 
} 

回答

5

一個簡單的方法來處理開頭的JSON元素名稱爲「 - 」,這是不能被用來爲Java標識符名稱的字符,是利用@SerializedName註解。

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