I have created a vaadin application using vaadin 14, i have a class accordion that passes an object HandlerTest to class Grid using a propertyChange listener. The object do pass to the grid class but when i try to use grid.setItems to show it it doesn't work. grid.setItems does add the object if i add it from the constructer but don't if i add it from the propertyChange methode.
Here is the code i used for bothe classes and the main class:
the Grid class:
`
package org.vaadin.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
#Route("grid")
public final class GridClass extends VerticalLayout implements PropertyChangeListener {
HandlerTest ht = new HandlerTest();
List<HandlerTest> list = new ArrayList<>();
Grid<HandlerTest> grid = new Grid<>();
public GridClass() {
grid.addColumn(HandlerTest::getPattern).setHeader("Pattern");
grid.addColumn(HandlerTest::getModuleName).setHeader("Module");
grid.setItems(list);
grid.getDataProvider().refreshAll();
grid.setAllRowsVisible(true);
grid.setHeight("480px");
add(grid);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
HandlerTest newHandler = (HandlerTest) evt.getNewValue();
ht = newHandler;
list.add(ht);
Notification.show("Value of obj :" + evt.getNewValue());
grid.getDataProvider().refreshAll();
}
}
`
here is the HandlerTest class:
`
package org.vaadin.example;
public class HandlerTest implements java.io.Serializable{
private String moduleName;
private String pattern;
private String method;
private String sourceType;
private String itemsPerPage;
private String mimesAllowed;
private String comments;
private String pSource;
public HandlerTest(String moduleName, String pattern, String method, String sourceType, String itemsPerPage, String mimesAllowed, String comments, String pSource) {
this.moduleName = moduleName;
this.pattern = pattern;
this.method = method;
this.sourceType = sourceType;
this.itemsPerPage = itemsPerPage;
this.mimesAllowed = mimesAllowed;
this.comments = comments;
this.pSource = pSource;
}
public HandlerTest() {
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getItemsPerPage() {
return itemsPerPage;
}
public void setItemsPerPage(String itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
public String getMimesAllowed() {
return mimesAllowed;
}
public void setMimesAllowed(String mimesAllowed) {
this.mimesAllowed = mimesAllowed;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getpSource() {
return pSource;
}
public void setpSource(String pSource) {
this.pSource = pSource;
}
#Override
public String toString() {
return moduleName + "/" + pattern + "/" + method + "/" + sourceType + "/" + itemsPerPage + "/" + mimesAllowed
+ "/" + comments + "/" + pSource ;
}
public HandlerTest createHandlerFromString(HandlerTest h){
String[] handlerText = (h.toString()).split("/");
HandlerTest handler = new HandlerTest(handlerText[0], handlerText[1], handlerText[2], handlerText[3],
handlerText[4], handlerText[5], handlerText[6], handlerText[7]);
return handler;
}
}
`
i was expecting the grid to be refreshed and the item is added but nothing happened. The notification shows the object to display but the grid don't add it.
I was following the start-up guide of at spring website https://spring.io/guides/gs/consuming-rest/.
I am not following the exact tutorial in the sense that I am using another endpoint: http://www.omdbapi.com?s=rush.
I am having an issue with JSON conversion to POJO. I am not getting any error or exceptions. Could someone point out where am I going wrong?
You can find the complete code here
Here are my POJOs:
package com.sample.restapi.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResponse {
private List<Search> search;
private String totalResults;
private String response;
public SearchResponse() {
}
public List<Search> getSearch() {
return search;
}
public void setSearch(List<Search> search) {
this.search = search;
}
public String getTotalResults() {
return totalResults;
}
public void setTotalResults(String totalResults) {
this.totalResults = totalResults;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#Override
public String toString() {
return "SearchResponse [search=" + search + ", totalResults=" + totalResults + ", response=" + response + "]";
}
}
Here is the Search.java
package com.sample.restapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Search {
private String title;
private String year;
private String imdbID;
private String type;
private String poster;
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Search [title=" + title + ", year=" + year + ", imdbID=" + imdbID + ", type=" + type + ", poster="
+ poster + "]";
}
}
Here is the driver class.
package com.sample.restapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
import com.sample.restapi.model.SearchResponse;
#SpringBootApplication
public class ConsumerApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumerApplication.class);
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SearchResponse searchResponse = restTemplate.getForObject("http://www.omdbapi.com?s=rush", SearchResponse.class);
log.info(searchResponse.toString());
}
}
The console output is :
14:34:12.941 [main] INFO com.sample.restapi.ConsumerApplication - SearchResponse [search=null, totalResults=344, response=null]
You are missing correct identifiers for the properties in the json, there are differences in the response and your classes in the Capital and lower case letters. Use #JsonProperty in your classes.
#JsonProperty("Search")
private List<Search> search = new ArrayList<Search>();
private String totalResults;
#JsonProperty("Response")
private String response;
you should also add #JsonProperty annotations in the Search class.
I am trying to convert json string in java bean using Gson but it is returnig null value.
public static void convert(String args) {
String json =
"{"body":{"response":{"total":"294","num":"294","filelist":[{"id":"56712","camname":"Camera1","camid":"514","start":"2016-07-08 12:00:38","end":"2016-07-08 12:03:00","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg","nvrip":"192.168.0.200:8095"},{"id":"56708","camname":"Camera1","camid":"514","start":"2016-07-08 11:58:14","end":"2016-07-08 12:00:36","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg","nvrip":"192.168.0.200:8095"},{"id":"56705","camname":"Camera1","camid":"514","start":"2016-07-08 11:55:49","end":"2016-07-08 11:58:11","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg","nvrip":"192.168.0.200:8095"},{"id":"56702","camname":"Camera1","camid":"514","start":"2016-07-08 11:53:25","end":"2016-07-08 11:55:47","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg","nvrip":"192.168.0.200:8095"},{"id":"56699","camname":"Camera1","camid":"514","start":"2016-07-08 11:51:00","end":"2016-07-08 11:53:22","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg","nvrip":"192.168.0.200:8095"}],"status":"OK"}}}";
// Now do the magic.
RecordingListResponseDTO data = new Gson().fromJson(json, RecordingListResponseDTO .class);
// Show it.
System.out.println("converted data :"+data);
}
My Bean Class is following.
RecordingListResponseDTO
public class RecordingListResponseDTO implements Serializable {
private String status;
private int total;
private int num;
List<FileListDTO> fileList;
public RecordingListResponseDTO(){
}
public RecordingListResponseDTO(String status, int total, int num, List<FileListDTO> fileList) {
this.status = status;
this.total = total;
this.num = num;
this.fileList = fileList;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List<FileListDTO> getFileList() {
return fileList;
}
public void setFileList(List<FileListDTO> fileList) {
this.fileList = fileList;
}
#Override
public String toString() {
return "RecordingListResponseDTO{" +
"status='" + status + '\'' +
", total=" + total +
", num=" + num +
", fileList=" + fileList +
'}';
}}
FileListDTO.java
public class FileListDTO {
private int id;
private String camname;
private int camid;
private Date start;
private Date end;
private int stream;
private String recReason;
private String filename;
private String snapshot;
private String nvrip;
public FileListDTO(int id, String camname, Date start, int camid, Date end, int stream, String recReason, String filename, String snapshot, String nvrip) {
this.id = id;
this.camname = camname;
this.start = start;
this.camid = camid;
this.end = end;
this.stream = stream;
this.recReason = recReason;
this.filename = filename;
this.snapshot = snapshot;
this.nvrip = nvrip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCamname() {
return camname;
}
public void setCamname(String camname) {
this.camname = camname;
}
public int getCamid() {
return camid;
}
public void setCamid(int camid) {
this.camid = camid;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public int getStream() {
return stream;
}
public void setStream(int stream) {
this.stream = stream;
}
public String getRecReason() {
return recReason;
}
public void setRecReason(String recReason) {
this.recReason = recReason;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getSnapshot() {
return snapshot;
}
public void setSnapshot(String snapshot) {
this.snapshot = snapshot;
}
public String getNvrip() {
return nvrip;
}
public void setNvrip(String nvrip) {
this.nvrip = nvrip;
}
#Override
public String toString() {
return "FileListDTO{" +
"id=" + id +
", camname='" + camname + '\'' +
", camid=" + camid +
", start=" + start +
", end=" + end +
", stream=" + stream +
", recReason='" + recReason + '\'' +
", filename='" + filename + '\'' +
", snapshot='" + snapshot + '\'' +
", nvrip='" + nvrip + '\'' +
'}';
}}
I am getting null value after converting Json string to Java object.
what I am doing wrong please suggest me.
Thank in advance.
Prerequisites:
Following JSON has been used:
{
"body":{
"response":{
"total":294,
"num":294,
"filelist":[
{
"id":56712,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 12:00:38",
"end":"2016-07-08 12:03:00",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56708,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:58:14",
"end":"2016-07-08 12:00:36",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56705,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:55:49",
"end":"2016-07-08 11:58:11",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56702,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:53:25",
"end":"2016-07-08 11:55:47",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56699,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:51:00",
"end":"2016-07-08 11:53:22",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg",
"nvrip":"192.168.0.200:8095"
}
],
"status":"OK"
}
}
}
Step 1:
Modify the declaration of private List<FileListDTO> fileList in RecordingListResponseDTO.java as follows:
#SerializedName("filelist")
private List<FileListDTO> fileList
Step 2:
Define following class MyDateTypeAdapter.java:
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class MyDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private DateFormat dateFormat;
public MyDateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
#Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
#Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Step 3:
Modify the method convert(String args) as follows:
public static void convert(String args) {
JsonParser parser = new JsonParser();
String json = parser.parse(args)
.getAsJsonObject()
.getAsJsonObject("body")
.getAsJsonObject("response")
.toString();
// Now do the magic.
RecordingListResponseDTO data = new GsonBuilder()
.registerTypeAdapter(Date.class, new MyDateTypeAdapter())
.create().fromJson(json, RecordingListResponseDTO.class);
// Show it.
System.out.println("converted data :"+data);
}
For testing purpose, you may try storing the JSON in a file i.e. D:/test.json and call the method by:
String json = new String(Files.readAllBytes(Paths.get("D:/test.json")));
convert(json);
something you need to change the models class like,
Initially in your json response data contains "body" tag that's represents to object, initially you need to create the class for object tag,then all data contains inside your "body" tag, so parse all data inside from body data,
may help this code,
public class RecordingListResponseDTO implements Serializable {
Recordinglist body;
public class Recordinglist(){
Recordresponse response;
public class Recordresponse(){
String total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
}
}
I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.
I'm having trouble retrieving latitude and longitude values from a given zip code. I'm attempting to do this via a Servlet, i.e. a zip code value is passed into the Servlet, and the Java code then uses the Google Geocode API to retrieve the latitude and longitude values, preferably in a String.
I've roamed all over the net for a simple sample, but there seems to be more Javascript and PHP methods for this than Java.
Could someone please paste a simple sample of how to extract the lat/long values in this manner?
Thanks in advance!!
-Rei
OK long answer. This is some code I have used succesfully to interrogate Google Geocode API. It requires to work with GSon but alternatively you can probably decode the answers manually if you don't want to use GSon:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.slf4j.Logger;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
public class GeoCoder {
private Gson gson = new Gson();
private volatile long lastRequest = 0L;
public GeocodeResponse getLocation(String... addressElements) throws JsonSyntaxException, JsonIOException, MalformedURLException,
IOException {
StringBuilder sb = new StringBuilder();
for (String string : addressElements) {
if (sb.length() > 0) {
sb.append('+');
}
sb.append(URLEncoder.encode(string.replace(' ', '+'), "UTF-8"));
}
String url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + sb.toString();
// Google limits this web service to 2500/day and 10 requests/s
synchronized (this) {
try {
long elapsed = System.currentTimeMillis() - lastRequest;
if (elapsed < 100) {
try {
Thread.sleep(100 - elapsed);
} catch (InterruptedException e) {
}
}
return gson.fromJson(new BufferedReader(new InputStreamReader(new URL(url).openStream())), GeocodeResponse.class);
} finally {
lastRequest = System.currentTimeMillis();
}
}
}
}
And the other classes:
GeocodeResponse:
import java.util.List;
public class GeocodeResponse {
public enum Status {
OK, ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED, INVALID_REQUEST;
}
public static class Result {
public static enum Type {
street_address,
route,
intersection,
political,
country,
administrative_area_level_1,
administrative_area_level_2,
administrative_area_level_3,
colloquial_area,
locality,
sublocality,
neighborhood,
premise,
subpremise,
postal_code,
natural_feature,
airport,
park,
point_of_interest,
post_box,
street_number,
floor,
room;
}
public static class AddressComponent {
private String long_name;
private String short_name;
private Type[] types;
public String getLong_name() {
return long_name;
}
public void setLong_name(String long_name) {
this.long_name = long_name;
}
public String getShort_name() {
return short_name;
}
public void setShort_name(String short_name) {
this.short_name = short_name;
}
public Type[] getTypes() {
return types;
}
public void setTypes(Type[] types) {
this.types = types;
}
}
private String formatted_address;
private List<AddressComponent> address_components;
private Geometry geometry;
private Type[] types;
public Type[] getTypes() {
return types;
}
public void setTypes(Type[] types) {
this.types = types;
}
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
public List<AddressComponent> getAddress_components() {
return address_components;
}
public void setAddress_components(List<AddressComponent> address_components) {
this.address_components = address_components;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
}
public static class Geometry {
public static enum LocationType {
ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE;
}
public static class ViewPort {
private Location northeast;
private Location southwest;
public Location getNortheast() {
return northeast;
}
public void setNortheast(Location northeast) {
this.northeast = northeast;
}
public Location getSouthwest() {
return southwest;
}
public void setSouthwest(Location southwest) {
this.southwest = southwest;
}
}
private Location location;
private LocationType location_type;
private ViewPort viewport;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public LocationType getLocation_type() {
return location_type;
}
public void setLocation_type(LocationType location_type) {
this.location_type = location_type;
}
public ViewPort getViewport() {
return viewport;
}
public void setViewport(ViewPort viewport) {
this.viewport = viewport;
}
}
private Status status;
private List<Result> results;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Location:
public class Location {
private double lat;
private double lng;
public Location() {
}
public Location(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}
This isn't as elegant as Guillaume Polet's answer, however it doesn't need additional libraries.
With the argument:
"1600 Amphitheatre Parkway, Mountain View, CA"
It prints the answer:
Latitude: 37.42207610
Longitude: -122.08451870
Here is the code:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class GoogleGeoCode
{
private static final String GEO_CODE_SERVER = "http://maps.googleapis.com/maps/api/geocode/json?";
public static void main(String[] args)
{
String code = args[0];
String response = getLocation(code);
String[] result = parseLocation(response);
System.out.println("Latitude: " + result[0]);
System.out.println("Longitude: " + result[1]);
}
private static String getLocation(String code)
{
String address = buildUrl(code);
String content = null;
try
{
URL url = new URL(address);
InputStream stream = url.openStream();
try
{
int available = stream.available();
byte[] bytes = new byte[available];
stream.read(bytes);
content = new String(bytes);
}
finally
{
stream.close();
}
return (String) content.toString();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private static String buildUrl(String code)
{
StringBuilder builder = new StringBuilder();
builder.append(GEO_CODE_SERVER);
builder.append("address=");
builder.append(code.replaceAll(" ", "+"));
builder.append("&sensor=false");
return builder.toString();
}
private static String[] parseLocation(String response)
{
// Look for location using brute force.
// There are much nicer ways to do this, e.g. with Google's JSON library: Gson
// https://sites.google.com/site/gson/gson-user-guide
String[] lines = response.split("\n");
String lat = null;
String lng = null;
for (int i = 0; i < lines.length; i++)
{
if ("\"location\" : {".equals(lines[i].trim()))
{
lat = getOrdinate(lines[i+1]);
lng = getOrdinate(lines[i+2]);
break;
}
}
return new String[] {lat, lng};
}
private static String getOrdinate(String s)
{
String[] split = s.trim().split(" ");
if (split.length < 1)
{
return null;
}
String ord = split[split.length - 1];
if (ord.endsWith(","))
{
ord = ord.substring(0, ord.length() - 1);
}
// Check that the result is a valid double
Double.parseDouble(ord);
return ord;
}
}