一尘不染

如何使用Java从Google地理编码序列化和反序列化JSON对象

json

我正在使用JSON中的Google Geocode响应。

JSON格式如下:

{
  "status": "OK",
  "results": [ {
  "types": [ "street_address" ],
  "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
  "address_components": [ {
     "long_name": "1600",
     "short_name": "1600",
     "types": [ "street_number" ]
  }, {
  "long_name": "Amphitheatre Pkwy",
  "short_name": "Amphitheatre Pkwy",
  "types": [ "route" ]
}, {
  "long_name": "Mountain View",
  "short_name": "Mountain View",
  "types": [ "locality", "political" ]
}, {
  "long_name": "California",
  "short_name": "CA",
  "types": [ "administrative_area_level_1", "political" ]
}, {
  "long_name": "United States",
  "short_name": "US",
  "types": [ "country", "political" ]
}, {
  "long_name": "94043",
  "short_name": "94043",
  "types": [ "postal_code" ]
} ],
"geometry": {
  "location": {
    "lat": 37.4219720,
    "lng": -122.0841430
  },
  "location_type": "ROOFTOP",
  "viewport": {
    "southwest": {
      "lat": 37.4188244,
      "lng": -122.0872906
    },
    "northeast": {
      "lat": 37.4251196,
      "lng": -122.0809954
    }
  }
}
} ]
}

我正在尝试使用Java创建序列化和反序列化它们。我尝试了GSON,但是因为它无法在更深层次上反序列化对象,所以GSON将不是一个选择。

我只是想知道是否有人对此主题有经验?也许您尝试过可以解决此问题的库?一些示例代码会很棒。

我真的不想为此编写自己的API …


阅读 230

收藏
2020-07-27

共1个答案

一尘不染

使用杰克逊

GoogleGeoCodeResponse result = mapper.readValue(jsonInOneString,GoogleGeoCodeResponse.class);

public class GoogleGeoCodeResponse {

     public String status ;
        public results[] results ;
        public GoogleGeoCodeResponse() {

        }
    }

     class results{
        public String formatted_address ;
        public geometry geometry ;
        public String[] types;
        public address_component[] address_components;
    }

     class geometry{
         public bounds bounds;
        public String location_type ;
        public location location;
        public bounds viewport;
    }

     class bounds {

         public location northeast ;
         public location southwest ;
     }

     class location{
        public String lat ;
        public String lng ;
    }

     class address_component{
        public String long_name;
        public String short_name;
        public String[] types ;
    }
2020-07-27