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

发布于 2024-12-02 13:10:41 字数 1309 浏览 0 评论 0原文

我正在使用 JSON 格式的 Google 地理编码响应。

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...

I am working with Google Geocode responses, which are in JSON.

The JSON format is as follows:

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

I am trying to create serialize and deserialize them using Java. I tried GSON, but because it cannot deserialize objects in a deeper level, GSON will not be an option.

I'm just wondering if anyone has experience on this topic? Perhaps you have tried a library that can solve this problem? Some sample code would be awesome.

I really don't want to write my own API for this...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

唯憾梦倾城 2024-12-09 13:10:41

使用杰克逊

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 ;
    }

Using Jackson

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 ;
    }
£噩梦荏苒 2024-12-09 13:10:41

如果有人有同样的问题,您可以使用 romu31 提供的 GoogleGeoCodeResponse :

public class GoogleGeoCodeResponse {
public String status;
public results[] results;

public GoogleGeoCodeResponse() {
}

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

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

public class bounds {

    public location northeast;
    public location southwest;
}

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

public class address_component {
    public String long_name;
    public String short_name;
    public String[] types;
}}

Gson API 例如:

 Gson gson = new Gson();
 GoogleGeoCodeResponse result = gson.fromJson(jsonCoord(URLEncoder.encode(address, "UTF-8"));

            GoogleGeoCodeResponse.class);

    double lat = Double.parseDouble(result.results[0].geometry.location.lat);

    double lng = Double.parseDouble(result.results[0].geometry.location.lng);

以及此函数到 得到它:

private String jsonCoord(String address) throws IOException {
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false");
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String jsonResult = "";
while ((inputLine = in.readLine()) != null) {
    jsonResult += inputLine;
}
in.close();
return jsonResult; 
}

if someone have same question you can use GoogleGeoCodeResponse provided by romu31 :

public class GoogleGeoCodeResponse {
public String status;
public results[] results;

public GoogleGeoCodeResponse() {
}

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

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

public class bounds {

    public location northeast;
    public location southwest;
}

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

public class address_component {
    public String long_name;
    public String short_name;
    public String[] types;
}}

and Gson API Ex:

 Gson gson = new Gson();
 GoogleGeoCodeResponse result = gson.fromJson(jsonCoord(URLEncoder.encode(address, "UTF-8"));

            GoogleGeoCodeResponse.class);

    double lat = Double.parseDouble(result.results[0].geometry.location.lat);

    double lng = Double.parseDouble(result.results[0].geometry.location.lng);

and this function to get it:

private String jsonCoord(String address) throws IOException {
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false");
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String jsonResult = "";
while ((inputLine = in.readLine()) != null) {
    jsonResult += inputLine;
}
in.close();
return jsonResult; 
}
池木 2024-12-09 13:10:41

您始终可以使用 http://www.jsonschema2pojo.org/
它会为你做这件事,而且你不需要手动做。


You can always use http://www.jsonschema2pojo.org/.
Which does it for you, and you don't have to manually do it.


身边 2024-12-09 13:10:41

尽管问题询问的是 JSON 序列化和反序列化,但尚不清楚您的真正目标是什么。可能您只是希望能够在 Java 代码中使用地理位置信息,在这种情况下,我建议几乎所有地理位置信息 API 都具有 Java SDK/客户端。以下是Google 的链接到 SmartyStreets,这是我熟悉的两项服务。

这是直接从 Google 存储库复制粘贴的示例。正如您所看到的,它使访问数据变得非常容易。

GeoApiContext context = new GeoApiContext().setApiKey("AIza...");
GeocodingResult[] results =  GeocodingApi.geocode(context,
    "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);

(全面披露:我曾在 SmartyStreets 工作过。)

Though the question asks about JSON serialization and deserialization, it's not clear what your real goal is. It could be that you just want to be able to use the geolocation information in Java code, and in that case I would suggest that almost all geolocation information APIs have Java SDKs/clients. Here is the link to Google's and to SmartyStreets's, which are two services I'm familiar with.

Here is an example copy-and-pasted straight from Google's repo. As you can see, it makes it very easy to access the data.

GeoApiContext context = new GeoApiContext().setApiKey("AIza...");
GeocodingResult[] results =  GeocodingApi.geocode(context,
    "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);

(Full disclosure: I have worked for SmartyStreets.)

甜扑 2024-12-09 13:10:41

Jackson是最好的,我利用了romu31提供的模型类,将jackson库放在类路径中,并使用Spring RestTemplate直接获取GeocodeResponse。

    public class GeocodeResponse {

    public String status;
    public results[] results;

    public GeocodeResponse() {
    enter code here
    }
}

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;
}

请注意,我只将 jackson 库放在类路径中,我什至不需要从 jackson 执行任何 API 方法,请参阅下面的测试代码

RestTemplate restTemplate = new RestTemplate();
        Map<String, String> vars = new HashMap<String, String>();

        vars.put("address", "Hong Kong");
        vars.put("sensor", "false");

        GeocodeResponse result = restTemplate.getForObject(
                "http://maps.googleapis.com/maps/api/geocode/json?address={address}&sensor={sensor}",
                GeocodeResponse.class, vars);

但是,此解决方案有一个小问题,类名和属性名不是够好了。这在某种程度上是不符合惯例的。
我知道我们可以将类名和属性名重构为更好的约定,但这意味着需要付出一定的努力来实现数据 marhsall 逻辑。

Jackson is the best, I made use of the model class provided by romu31, put the jackson library in class path and use the Spring RestTemplate to get the GeocodeResponse directly.

    public class GeocodeResponse {

    public String status;
    public results[] results;

    public GeocodeResponse() {
    enter code here
    }
}

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;
}

Please note I only put the jackson library in classpath, I don't even need to execute any API method from jackson, please see my test codes below

RestTemplate restTemplate = new RestTemplate();
        Map<String, String> vars = new HashMap<String, String>();

        vars.put("address", "Hong Kong");
        vars.put("sensor", "false");

        GeocodeResponse result = restTemplate.getForObject(
                "http://maps.googleapis.com/maps/api/geocode/json?address={address}&sensor={sensor}",
                GeocodeResponse.class, vars);

However, there is a minor issue on this solution, the class names and property names are not nice enough. It's somehow in bad convention.
I know that we can refactor the class name and property names into better convention, but it would imply certain effort to implement the data marhsall logic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文