回答編集履歴

2

コード修正

2022/12/29 06:16

投稿

jimbe
jimbe

スコア13170

test CHANGED
@@ -100,7 +100,13 @@
100
100
  ---
101
101
  真面目に構造作って Jackson でオブジェクト化するとか。
102
102
  ```java
103
+ import com.fasterxml.jackson.core.JsonProcessingException;
104
+ import com.fasterxml.jackson.databind.JsonMappingException;
105
+ import com.fasterxml.jackson.databind.ObjectMapper;
106
+
107
+ public class Main {
108
+
103
- static class GoogleResult {
109
+ static class GoogleGeocodeResponse {
104
110
  static class Result {
105
111
  static class AddressComponent {
106
112
  public String long_name;
@@ -131,7 +137,13 @@
131
137
 
132
138
  public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
133
139
  ObjectMapper mapper = new ObjectMapper();
134
- GoogleResult gr = mapper.readValue(json, GoogleResult.class);
140
+ GoogleGeocodeResponse response = mapper.readValue(json, GoogleGeocodeResponse.class);
141
+ for(GoogleGeocodeResponse.Result result : response.results) {
135
- System.out.println("lat="+gr.results[0].geometry.location.lat+", lng="+gr.results[0].geometry.location.lng);
142
+ System.out.println("lat="+result.geometry.location.lat+", lng="+result.geometry.location.lng);
143
+ }
136
144
  }
145
+
146
+ static final String json = "{\n"
147
+ //データ略
148
+ }
137
149
  ```

1

真面目版追加

2022/12/29 06:08

投稿

jimbe
jimbe

スコア13170

test CHANGED
@@ -97,3 +97,41 @@
97
97
  ```
98
98
  lat=35.6717816, lng=139.7418364
99
99
  ```
100
+ ---
101
+ 真面目に構造作って Jackson でオブジェクト化するとか。
102
+ ```java
103
+ static class GoogleResult {
104
+ static class Result {
105
+ static class AddressComponent {
106
+ public String long_name;
107
+ public String short_name;
108
+ public String[] types;
109
+ }
110
+ static class Geometry {
111
+ static class Position {
112
+ public double lat, lng;
113
+ }
114
+ static class Area {
115
+ public Position northeast, southwest;
116
+ }
117
+ public Area bounds;
118
+ public Position location;
119
+ public String location_type;
120
+ public Area viewport;
121
+ }
122
+ public AddressComponent[] address_components;
123
+ public String formatted_address;
124
+ public Geometry geometry;
125
+ public String place_id;
126
+ public String[] types;
127
+ }
128
+ public Result[] results;
129
+ public String status;
130
+ }
131
+
132
+ public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
133
+ ObjectMapper mapper = new ObjectMapper();
134
+ GoogleResult gr = mapper.readValue(json, GoogleResult.class);
135
+ System.out.println("lat="+gr.results[0].geometry.location.lat+", lng="+gr.results[0].geometry.location.lng);
136
+ }
137
+ ```