使用Gson获取Json数据

时间:2016-06-18 18:09:55

标签: android gson

我想得到纬度和经度的地方。但我没有得到数据。我正在使用Gson Library来获取数据。我不明白我在做什么? 这是我在Main片段中的代码。

    private class PostFetcher extends AsyncTask<Void,Void,String>{
    private static final String TAG = "PostFetcher";
    private static final String SERVER_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&name=cruise&key=My key here";
    @Override
    protected String doInBackground(Void... params) {

        Reader reader= API.getData(SERVER_URL);

        try {


            Gson gson=new GsonBuilder().create();
            try
            {
                JsonPlaces jsonplaces=gson.fromJson(reader,JsonPlaces.class);
                System.out.println("\n\nData=\n\n"+jsonplaces);
            }
            catch (IllegalStateException | JsonSyntaxException exception)
            {
               System.out.println("Json Exception is :" + exception);
            }


        } catch (Exception ex) {
            Log.e(TAG, "Failed to parse JSON due to: " + ex);

        }
        return null;
    }
}

这是我获取数据的API类:

    public class API {
private static Reader reader=null;

public static Reader getData(String SERVER_URL) {
    StatusLine statusLine=null;
    HttpResponse response=null;
    try {

        //Create an HTTP client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            response = httpClient.execute(httpPost);
            statusLine = response.getStatusLine();

            if (statusLine.getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                reader = new InputStreamReader(content);
            }
        }catch(ClientProtocolException e){
            e.printStackTrace();
        }catch(IllegalStateException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        return reader;

}
}

这是JSONPlaces类中的代码,

    public class JsonPlaces {

@SerializedName("html_attributions")
private List<String> html_attributions;
@SerializedName("results")
private List<Results> results;
@SerializedName("status")
private String status;

public List<Results> getResults(){
    return results;
 }
 }

我的结果calss:

    public class Results {

     @SerializedName("id")
     private String id;
     @SerializedName("name")
     private String name;
     @SerializedName("geometry")
     private Geometry geometry;

  public String getId(){
    return id;
   }
   public String getName(){
    return name;
   }

    public Geometry getGeometry(){
    return geometry;
   }
   }

我的几何课程:

  public class Geometry {

     @SerializedName("location")
    private PlaceLocation placelocation;

   public PlaceLocation getPlacelocation(){
    return placelocation;
    }
    }

PlaceLocation类:

public class PlaceLocation {

       @SerializedName("lat")
      private double latitude;
      @SerializedName("lng")
      private double longitude;

     public double getLatitude(){
        return latitude;
     }
    public double getLongitude(){
       return longitude;
    }
    }

浏览器中的Json响应:

           {
    "html_attributions" : [],
    "results" : [
     {
     "geometry" : {
        "location" : {
           "lat" : -33.86755700000001,
           "lng" : 151.201527
        }
     },
     "icon" :    "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "ce4ffe228ab7ad49bb050defe68b3d28cc879c4a",
     "name" : "Sydney Showboats",
     "opening_hours" : {
        "open_now" : false,
        "weekday_text" : []
     },
     "photos" : [
        {
           "height" : 750,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/107415973755376511005/photos\"\u003e           Sydney Showboats\u003c/a\u003e"
           ],
             "photo_reference" :  "CoQBcwAAAKUutk4re5CLfulmsz_4LeTG_5dhWuws7gnSKKDZcuUBosX4UahUozZTgUZimLJwV_bga2j X0fKzJyN9D-PePi41rrrVG9UgPfzxuHm_9xcSfwrN4UfebxEtzApFSvNpSNMppfOK8xgeVyUJXUc-McalViyC6OXyX7-WPz8Wd8RZEhBiJ_8TvAYCqoRNq8Heu3nuGhR9YAkOdsf1L9mjltLiDyozdIq7yg",
           "width" : 1181
        }
     ],
     "place_id" : "ChIJjRuIiTiuEmsRCHhYnrWiSok",
     "rating" : 4.3,
     "reference" : "CnRkAAAAX5DC1NPM2UjaxgF1C_coeWDC_CNVXSC6tncsttukOv37SdomXLJucWcsu3dH2CW-9cJfZ8raPI74dWlvnvuT3K9vPtqDW0ao53JkGrYJ_8__C970YyuKa-l96PjNLXd4BD7T3RrFwcLTrWhDLtfVFRIQlZaPcZUxoBnvsrj-dYooaRoUjCTduDP030huxJA_xT1GqjmiGzU",
     "scope" : "GOOGLE",
     "types" : [
        "travel_agency",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
       ],
      "vicinity" : "King Street Wharf 5, Lime Street, Sydney"
     },
    {
     "geometry" : {
        "location" : {
           "lat" : -33.8686058,
           "lng" : 151.2018207
        }
      },
     "icon" :  "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
     "name" : "Rhythmboat Cruises",
     "photos" : [
        {
           "height" : 480,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/104066891898402903288/photos\"\u003eRhythmboat Cruises\u003c/a\u003e"
           ],
           "photo_reference" : "CoQBcwAAAMnvNxTmiw3WZ7ePhICm_8qhylIz0-CdAeMcJJ4PEORp08NJAuxmNyCL9M2caY_vy1hz3lncZbFCh_jo4c7Vfw9TKh9EGJHdPNvxo16ma4cXh1gnmslCF7rVwgtQGmpycceyuZRYOI6pDsuZtpasze8jYJo21TS7h83WqGZlQ-7bEhATPLPhd5G9XqSIfncs2gdEGhTrK1VedQPBLt32n_IvDoQPmbXoJQ",
           "width" : 640
        }
      ],
      "place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
      "rating" : 4.2,
     "reference" : "CnRmAAAA6rbrg4EUKVOUReV2Bmn2z4zuHe4Ukh4rLnzzMzhIwddLb8AWpffXzimjf9I5EtQXLTX0yBkauaSkh9W1bViye0gqqjvUIytPmpKxgXTPzqG5G_mP7wqhYK8bqvLhh1lEVdipU8OsNsTZsXzRrEfEYBIQcMwEKY2AOlEOc3cA37Y81RoUUwgHM59WLv8-OUeXLxCRc7baXw8",
      "scope" : "GOOGLE",
      "types" : [
        "travel_agency",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
       ],
       "vicinity" : "King Street Wharf, King Street, Sydney"
  },
  {
     "geometry" : {
        "location" : {
           "lat" : -33.867591,
           "lng" : 151.201196
        }
     },
     "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "a97f9fb468bcd26b68a23072a55af82d4b325e0d",
     "name" : "Australian Cruise Group",
     "opening_hours" : {
        "open_now" : false,
        "weekday_text" : []
     },
       "photos" : [
        {
           "height" : 328,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/110751364053842618118/photos\"\u003eAustralian Cruise Group\u003c/a\u003e"
           ],
           "photo_reference" : "CoQBcwAAAHIivSwUq-TxwmTBVInY_5QWPuFVcRAZmbTFPVcTvEvgTf0W59be9f7UthoA1AHIvKqnIP3pVky51PdTNirLdPXnh7ae5MOYwfNt1Ld72aa9B9dwzUoYHYRDWlwcE_WB11X2XqQTQ-xUWfegAE6ZN-Bfqy8_Qvz0reQAXFsFQ149EhA8OSryvknsThnrwQozzJSOGhQaxN9kONclP9IijaRzVudkgv7ARQ",
           "width" : 329
        }
     ],
       "place_id" : "ChIJrTLr-GyuEmsRBfy61i59si0",
       "reference" : "CnRqAAAAh4WzQoBul104P5DsKrC2csOire9KA57fCw6km6PKsxL9F-MBCxFHTGM9hOkut_6YkpbEEJgRDBt_wov5Xz4f9-2b35ZKFr93Uk8SsS-rOruSIUAIJwrsKDg3yoHCK6J-A6Xndix4haZloQLzThSxGRIQqux-aXkP6OkRMbL1H6W46RoUdtpPU0qBKEmxwm9YfN6yaxtONIU",
       "scope" : "GOOGLE",
       "types" : [
        "travel_agency",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
     ],
     "vicinity" : "32 The Promenade, King Street Wharf 5, Sydney"
     },
      {
       "geometry" : {
        "location" : {
           "lat" : -33.8709434,
           "lng" : 151.1903114
        }
       },
       "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "3458f23c154e574552e0722773a46f384816b241",
     "name" : "Vagabond Cruises",
     "opening_hours" : {
        "open_now" : false,
        "weekday_text" : []
       },
       "photos" : [
        {
           "height" : 1067,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/101516907347198229066/photos\"\u003eVagabond Cruises\u003c/a\u003e"
           ],
           "photo_reference" : "CoQBcwAAAA7gDQiMEMAKEN_HDq5LU2IuSCyTBMJ22xolPMoNgMkyC_RHPdXhQexlVXciVf6wdVkd1j7uYz6R4KcxmNiSCm83_9eQAxE5CfJI1FRhxjuaVcxakk0ybU9EcKkJ7LTA8c0XwKCQQspa6wAwSTvPaOvew5lPeRqIJKMR3e8X8dH8EhAPojq_vipFXst4dgKeqfp1GhQYR5Ukv8V3Y5D3bgQVqTrRwiKkuA",
           "width" : 1600
        }
       ],
     "place_id" : "ChIJLfySpTOuEmsRMFymbMkVkOE",
     "rating" : 4.1,
     "reference" : "CnRkAAAA_cLaWta9QrknzbzpdC_PBq6inoy2wFbdr5w1rfNTGFnx2lLvbYUXj5e3IPl2Qk3B7LTv69rJioiodtUfOMwV8L7xjnXZ7BimCx-RcLE50CHBLnQuqHAi7NXWhsuElfh_QtXBmI83TBv4VzTTQg6jcRIQ9efx_bt2UBKrqnVrjhR8jhoU9PzTBBNxoo_gsuWQmQfK1TL4PCc",
        "scope" : "GOOGLE",
        "types" : [
        "travel_agency",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
        ],
        "vicinity" : "37 Bank Street, Pyrmont"
      },
     {
     "geometry" : {
        "location" : {
           "lat" : -33.867551,
           "lng" : 151.200817
        }
        },
     "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "b0277cade7696e575824681aba949d68814f9efe",
     "name" : "Sydney New Year's Eve Cruises",
     "opening_hours" : {
        "open_now" : false,
        "weekday_text" : []
        },
       "photos" : [
        {
           "height" : 1152,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/107666140764925298472/photos\"\u003eSydney New Year&#39;s Eve Cruises\u003c/a\u003e"
           ],
           "photo_reference" : "CoQBcwAAAFaGoAjnBfA6W_dYDkSCb548Z5IocZea2RVRX4MjS3MJGtuTBurbY8c-5j_J8glr3M8mXkuJwL-1lZDzTksUDIlaUj882PvuHJHOKKBqngZr4bL5X04ZjLpA01zvVIs8b6Bk6K1CWn8dytd4vVwqsyCHCrG1chl2sMHhX7IL3NM2EhD3tcdIZI2Df1D8DmWaSFTwGhSPb6TfSF02-8Ys8q76Fd-MptSxDg",
           "width" : 2048
        }
       ],
       "place_id" : "ChIJ__8_hziuEmsR27ucFXECfOg",
       "reference" : "CoQBcQAAAJ-IO8QY9jm-yziMw9aLyALi9Cu1-tnPqoA9FdNrfGVYiTm56N3Y-AdrEGbEhZcy5pVuqvHVBfz3fddFfO6O8cJRfvfC73swdAt1BcLgy80YbUXQgCQYxDD4WA8YJKEAxmAKkuCCKOy1I5TTBMYcq8iWtdqJbPrA34vfJkd8DSzwEhCsKWP9OhD8iZAUZMSTIT9mGhSfHwx8kUiQ2DayEndAxX9k3BBB4A",
       "scope" : "GOOGLE",
       "types" : [
        "travel_agency",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
        ],
     "vicinity" : "32 The Promenade, King Street Wharf 5, Sydney Nsw 2000, Sydney"
       },
       {
         "geometry" : {
        "location" : {
           "lat" : -33.86724419999999,
           "lng" : 151.2017012
        }
       },
        "icon" :   "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
       "id" : "c620902a8565dd4c4d605fecbe4f9b585d881b62",
       "name" : "Blue Line Cruises",
        "place_id" : "ChIJvwSIiTiuEmsR8hEazPa4W7U",
         "reference" : "CnRlAAAAQ-d7744Z_XymkoVLcfRtZzaBTIEnpFIFm5pV9yu- IleAELeQY-01VvrvSfJ4pROIyNHXVNUAIx7WIZUwphbiBPTMT38dfdOw2Yae- T980OLJ5Rv4aQWdhL9nlIFsuV0RHgixOjOOGYsydMhA1MfPWRIQofFEBDRdT7IdwDRvRInHrxoUn7BLJ GjJhghPjDgYa424VwvsmPI",
       "scope" : "GOOGLE",
       "types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
       "vicinity" : "Australia"
      }
     ],
     "status" : "OK"
     }

我的日志:

             6-18 20:16:35.707 13357-13357/? I/SELinux: Function:   selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-  G361H_5.1.1_0045
    06-18 20:16:35.707 13357-13357/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
    06-18 20:16:35.707 13357-13357/? I/art: Late-enabling -Xcheck:jni
    06-18 20:16:35.727 13357-13357/? I/SAMP: ActivityThread() - SAMP_ENABLE : true
    06-18 20:16:35.747 13357-13357/? D/ContextImpl: ContextImpl running for user UserHandle{0} 0
    06-18 20:16:35.777 13357-13357/com.example.shahik.androidtask D/ContextImpl: ContextImpl running for user UserHandle{0} 0
   06-18 20:16:35.777 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
   06-18 20:16:35.827 13357-13357/com.example.shahik.androidtask D/ContextImpl: ContextImpl running for user UserHandle{0} 0
   06-18 20:16:35.857 13357-13357/com.example.shahik.androidtask D/ContextImpl: ContextImpl running for user UserHandle{0} 0
  06-18 20:16:35.857 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
  06-18 20:16:35.957 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
  06-18 20:16:35.957 13357-13357/com.example.shahik.androidtask D/DisplayManager: DisplayManager()
  06-18 20:16:35.997 13357-13357/com.example.shahik.androidtask D/PhoneWindow: *FMB* installDecor mIsFloating : false
  06-18 20:16:35.997 13357-13357/com.example.shahik.androidtask D/PhoneWindow: *FMB* installDecor flags : -2139029248
  06-18 20:16:36.127 13357-13401/com.example.shahik.androidtask D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: false
  06-18 20:16:36.137 13357-13357/com.example.shahik.androidtask D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
  06-18 20:16:36.137 13357-13357/com.example.shahik.androidtask D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
  06-18 20:16:36.167 13357-13357/com.example.shahik.androidtask I/zzx: Making Creator dynamically
  06-18 20:16:36.177 13357-13357/com.example.shahik.androidtask D/ContextImpl: ContextImpl running for user UserHandle{0} 0
  06-18 20:16:36.177 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
  06-18 20:16:36.177 13357-13357/com.example.shahik.androidtask W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
  06-18 20:16:36.177 13357-13402/com.example.shahik.androidtask I/System.out: Thread-16033(ApacheHTTPLog):Reading from variable values from setDefaultValuesToVariables
   06-18 20:16:36.177 13357-13357/com.example.shahik.androidtask W/Reso urcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
   06-18 20:16:36.177 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
   06-18 20:16:36.177 13357-13402/com.example.shahik.androidtask I/System.out: Thread-16033(ApacheHTTPLog):isSBSettingEnabled false
   06-18 20:16:36.177 13357-13402/com.example.shahik.androidtask I/System.out: Thread-16033(ApacheHTTPLog):isShipBuild true
  06-18 20:16:36.177 13357-13402/com.example.shahik.androidtask I/System.out: Thread-16033(ApacheHTTPLog):SMARTBONDING_ENABLED is false
  06-18 20:16:36.177 13357-13402/com.example.shahik.androidtask I/System.out: Thread-16033(ApacheHTTPLog):SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
  06-18 20:16:36.227 13357-13357/com.example.shahik.androidtask D/ContextImpl: ContextImpl running for user UserHandle{0} 0
  06-18 20:16:36.227 13357-13357/com.example.shahik.androidtask W/ResourcesManager: getTopLevelResources: null for user  0
  06-18 20:16:36.237 13357-13357/com.example.shahik.androidtask D/ChimeraCfgMgr: Reading stored module config
  06-18 20:16:36.237 13357-13371/com.example.shahik.androidtask I/art: Background sticky concurrent mark sweep GC freed 8320(544KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 7MB/7MB, paused 5.554ms total 41.442ms
  06-18 20:16:36.298 13357-13357/com.example.shahik.androidtask D/ChimeraFileApk: Primary ABI of requesting process is armeabi-v7a
  06-18 20:16:36.298 13357-13357/com.example.shahik.androidtask D/ChimeraFileApk: Classloading successful. Optimized code found.
  06-18 20:16:36.358 13357-13357/com.example.shahik.androidtask I/Google Maps Android API: Google Play services client version: 7095000
  06-18 20:16:36.368 13357-13357/com.example.shahik.androidtask I/Google Maps Android API: Google Play services package version: 9083234
  06-18 20:16:36.688 13357-13357/com.example.shahik.androidtask I/c: Token loaded from file. Expires in: 93433486 ms.
  06-18 20:16:36.688 13357-13357/com.example.shahik.androidtask I/c: Scheduling next attempt in 93133 seconds.
  06-18 20:16:36.878 13357-13442/com.example.shahik.androidtask I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
  06-18 20:16:36.878 13357-13442/com.example.shahik.androidtask I/System.out: (HTTPLog)-Static: isShipBuild true
  06-18 20:16:36.878 13357-13442/com.example.shahik.androidtask I/System.out: (HTTPLog)-Thread-16037-904285906: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
  06-18 20:16:36.878 13357-13442/com.example.shahik.androidtask I/System.out: (HTTPLog)-Thread-16037-904285906: SMARTBONDING_FEATURE_ENABLED is false
  06-18 20:16:36.888 13357-13442/com.example.shahik.androidtask I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
  06-18 20:16:36.988 13357-13401/com.example.shahik.androidtask I/OpenGLRenderer: Initialized EGL, version 1.4
  06-18 20:16:36.988 13357-13401/com.example.shahik.androidtask D/OpenGLRenderer: Enabling debug mode 0
  06-18 20:16:37.108 13357-13357/com.example.shahik.androidtask D/ListView: change accessibility focus position = 0
  06-18 20:16:37.178 13357-13357/com.example.shahik.androidtask I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2e45ac99 time:47278573
  06-18 20:16:38.089 13357-13444/com.example.shahik.androidtask I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
  06-18 20:16:38.440 13357-13443/com.example.shahik.androidtask I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
  06-18 20:16:39.210 13357-13402/com.example.shahik.androidtask I/System.out: AsyncTask #1 calls detatch()
  06-18 20:16:39.210 13357-13402/com.example.shahik.androidtask I/System.out: Data=
   06-18 20:16:39.210 13357-13402/com.example.shahik.androidtask I/System.out: JsonFetcher.JsonPlaces@15e21f1

1 个答案:

答案 0 :(得分:0)

我必须同意创建POJO类比其他许多方法更舒服,但在这种情况下,您需要定义多个POJOS,例如使用webtool like this 或者以更有创意的方式做到这一点......

这就是我的建议......

忘记POJOS并从服务器响应

获得您需要的内容

实施例

这将采用您发布的示例并打印纬度和纬度

JsonParser parser = new JsonParser();
JsonObject o = parser.parse(jsonResponse).getAsJsonObject();
JsonArray results = o.getAsJsonArray("results");
for (JsonElement jsonElement : results) {
    System.out.println("Lat: " + jsonElement.getAsJsonObject().get("geometry").getAsJsonObject().get("location")
            .getAsJsonObject().get("lat"));
    System.out.println("Lon: " + jsonElement.getAsJsonObject().get("geometry").getAsJsonObject().get("location")
            .getAsJsonObject().get("lng"));
}