A JSONArray text must start with '[' at 2 [character 3 line 1] - java

I have written the following code to get the JSON response from the url which has authentication. Further,this response is in the format of the JSON array. Response is kind of big so I have attached JSON response in the following link:
https://drive.google.com/file/d/1-gSM1CXQlB7eJQXXsY8_G3koJWuyZB8S/view?usp=sharing
I want to fetch the user id and their role in the form of JSON object. However I'm facing this error.Can anybody help me what went wrong and could you suggest any modification in the code?
package url_request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParing {
private static HttpURLConnection connection;
public static void main(String args[]) {
String usernameColonPassword = "uname:pass";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("https://ucf6-zfon-fa-ext.oracledemos.com/hcmRestApi/scim/Users");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
// for testing the connection
// System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
// System.out.println(responseContent.toString());
parse(responseContent.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection.disconnect();
}
}
public static String parse(String responseBody) {
JSONArray albums;
try {
albums = new JSONArray(responseBody);
for (int i = 0; i < albums.length(); i ++) {
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int role = album.getInt("roles");
System.out.println(id + " " + role);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
In the uname and pass fields, I will add the credential of the URL.

This code works for your example, althought I had to change some types, there were problems with casting
public static Map<String, Set<String>> parse(String responseBody) {
JSONObject resourcesNode = new JSONObject(responseBody); // incoming payload is an object, not an Array
Map<String, Set<String>> result = new HashMap<>();
try {
JSONArray albums = resourcesNode.getJSONArray("Resources"); // get to the
//Resource array, that holds desired data
for (int i = 0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
String id = album.getString("id"); //id was type of String, not int
if(album.has("roles")){ // not all entries had roles, safety check
Set<String> userRoles =new HashSet<>();
JSONArray roles = album.getJSONArray("roles");
for(int j=0;j<roles.length();j++){
userRoles.add(roles.get(j).toString());
}
results.put(id, userRoles);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}

Related

How To Receive data from website using JSON for android?

I created a class for my android application that connects to mysql database using json.. note that the php code getNews.php is tested and it responds with the required data in json format properly. And note that i only want to get an array containing the data with this class ArrayReceiver.java ... it isn't working though... can anyone check the code please.
ArrayReceiver.java
package com.example.batoul.uptodate4;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArrayReceiver extends AsyncTask<String, Integer, String> {
List<Article> a=new ArrayList<Article>();
String url="192.168.11.8/utd/getNews.php";
Boolean error = false;
private ProgressDialog pDialog;
Boolean success = false;
String msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public List<Article> getA() {
return a;
}
#Override
protected String doInBackground(String... arg) {
publishProgress(2);
// agendaArrayList = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>();
try {
// params.add(new BasicNameValuePair("notActivated", "false"));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url,
ServiceHandler.POST, params);
// Log.e("aaa ", "> " + ServiceHandler.url);
// Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
//int catObj22 = jsonObj.getInt("success");
// if (catObj22 == 1) {
JSONArray titles = jsonObj.getJSONArray("title");
for (int i = 0; i < titles.length(); i++) {
String catObj = (String) titles.get(i);
Article obj = new Article(0,"");
obj.setTitle(catObj);
a.add(obj);
}
success = true;
} else {
success = false;
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
} catch (Exception e) {
error = true;
return null;
}
Log.e("aaa ", " success");
return "success";
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if (pDialog.isShowing()) {
// pDialog.dismiss();
// }
// Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
if (success) {
// for (int i = 0; i < travelsArr.size(); i++) {
// new getPic().execute("" + i);
// }
//ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
//SubjectListView.setAdapter(adapter);
}
}
}
ServiceHandler.java
package com.example.batoul.uptodate4;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public static String url ,u;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
this.url =url +"?" + paramString;
}
HttpGet httpGet = new HttpGet(this.url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
getNews.php :
<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
$query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
array_push($title, $row["title"]);// need change
}
$response["success"] = 1;
$response["title"] = $title;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>

Converting JSONObject to JSONArray Exception

I have a website that I have to make queries on in Java. Here you can see the dataset
https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31
At the very first beginning, I thought this is a JSONArray, but Eclipse always told me, it is not.
So therefore I tried to convert from JSONObject to JSONArray but I get this error:
org.json.JSONException: JSONObject["dataset"] is not a JSONArray.
What am I doing wrong?
Here is my code:
package query;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Stockquery {
public static void main(String[] args) {
String jsonString = callURL(
"https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31");
// System.out.println("\n\njsonString: " + jsonString);
try {
JSONObject jsonobjects = new JSONObject(jsonString);
System.out.println("\n\njsonArray: " + jsonobjects);
JSONArray arr = jsonobjects.getJSONArray("dataset");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String callURL(String myURL) {
// System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
The dataset field of jsonobjects is a JSONObject not JSONArray. Change this:
jsonobjects.getJSONArray("dataset");
to this:
JSONObject dataset = jsonobjects.getJSONObject("dataset");
JSONArray array = dataset.getJSONArray("data");

I'm using the answer from another SO post and I'm getting an exception JSONArray cannot be converted to JSONObject. How can I get this resolved?

Here is the answer I'm using How to implement Login with HttpURLConnection and PHP server in Android
Here is my JSONParser.java:
package com.example.android.simplejson;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn; // Connection
DataOutputStream wr; // Write
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL("my_url");
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
try {
urlObj = new URL("my_url");
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
Log.d("Response: ", "> " + line); //here you'll get the whole response
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
Here is a snippet of my MainActivity.java:
class checkLogin extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pd;
private static final String LOGIN_URL = "my_url";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Attempting login...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
protected JSONObject doInBackground(String... params) {
try {
HashMap<String, String> credentials = new HashMap<>();
credentials.put("username", params[0]);
credentials.put("password", params[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", credentials);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (json != null) {
Toast.makeText(MainActivity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1) {
Log.d("Success!", message);
} else {
Log.d("Failure", message);
}
}
}
}
It gets a JSONArray from the server [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]
My problem is the JSONArray can't be converted to JSONObject. So what can I change in my code to return the JSONArray as jObj? My ultimate goal is to set the text in my main activity as [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}].
Thanks!
You can't parse a JSON array as a JSON object. First you have to parse the payload as an array and then get the object from it.
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
// ...
try {
JSONArray jArr = new JSONArray(result.toString());
jObj = jArr.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
Refer the below exampe :
String str = {"xyz":[{"name":"apple","email_id":"apple#apple.com"}]};
JSONObject json = JSONObject.fromObject(str);
So essentially your response is in format of a JSONArray [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]'
where it should have been something like
{"response": [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]}
or simply
{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}
depending on your preference. If you are always going to return a single JSONObject (probably as this is a login service response) there is no need to use the square braces which makes it a JSONArray.

How to fetch JSON object from Json array in REST API

I am new to REST API and handling JSON in our automation script. I have an API whose response is JSONArray i.e.,
[{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
While automation, for verification I need to fetch the reponse. I have tried the below one but not getting expected output
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.*;
public class ProjectNameVerfication {
public static void main(String[] args) throws JSONException
{
try
{
URL url = new URL("http://17*.**.**.**:3000/api/******");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200)
{
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
System.out.println("str : " + str);
JSONObject obj = new JSONObject(str.substring(str.indexOf('{')));
System.out.println("obj : " +obj);
int ProjectID = obj.optInt("ProjectID");
String ProjectName = obj.getString("ProjectName");
System.out.println("ProjectID: " +ProjectID);
System.out.println("ProjectName: " +ProjectName);
JSONArray arr = obj.getJSONArray("ProjectID");
for (int i = 0; i < arr.length(); i++)
{
String post_id =arr.getJSONObject(i).getString("ProjectName");
}
conn.disconnect();
}
catch (MalformedURLException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace(); }
}
}
Actual output is bellow:
str : [{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
obj : {"ProjectName":" securities""ProjectID":15}
ProjectID: 15
ProjectName: Securities
Exception in thread "main" org.json.JSONException: JSONObject["ProjectID"] is not a JSONArray.
at org.json.JSONObject.getJSONArray(JSONObject.java:539)
at MyTest.ProjectNameVerfication.main(ProjectNameVerfication.java:60)
You want to get all ProjectName,right?
look at your response data:
[{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
it is already a JSONArray string,you can parse it as JSONArray ,and get ProjectName in foreach
JSONArray jsonArray = new JSONArray("your str");
for (Object object : jsonArray) {
JSONObject jsonObject = (JSONObject)object;
System.out.println(jsonObject.toString());
}
If you are using simple JSON you have to parse as follows.
String str="[{\"ProjectID\":15,\"ProjectName\":\" Securities\"},
{\"ProjectID\":16,\"ProjectName\":\"PAS \"}]";
JSONParser json=new JSONParser();
try {
JSONArray arr=(JSONArray)json.parse(str);
for (int i = 0; i < arr.size(); i++) {
JSONObject obj=(JSONObject)arr.get(i);
System.out.println("ProjectID: "+obj.get("ProjectID"));
System.out.println("ProjectName: "+obj.get("ProjectName"));
}
} catch (ParseException e) {
e.printStackTrace();
}
Your response is an Array so you need JSONArray instead of JSONObject.
try {
JSONArray e = new JSONArray(str);
int l = e.length();
for (int x = 0; x < l; x++) {
JSONObject object1 = e.getJSONObject(x);
String projectID = object1.getString("ProjectID");
String projectName = object1.getString("ProjectName");
}
} catch (JSONException e) {
e.printStackTrace();
}

How to send a Google Places Search Request with Java

I need to search Goolge Places Pages by long/lat for any banks in the area of 20m.
This Google Places Doc describes how to do it with JavaScript. They are using a google.maps.LatLng Object that i don't have in Java.
Does anyone now how to call the Service?
Maybe there is also an Java API for Goolge Places?
Best Regards,
Christian.
Edit 1:
I found someone constructing the url like this:
String url = baseUrl + "location=" + lat + "," + lon + "&" +
"radius=" + searchRadius + "&" + types + "&" + "sensor=true" +
"&" + "key=" + googleAPIKey;
Answer: Edit 2:
I because of the post above i found out how to do it. This is a example how to send the request:
public class GooglePlacesClient
{
private static final String GOOGLE_API_KEY = "***";
private final HttpClient client = new DefaultHttpClient();
public static void main(final String[] args) throws ParseException, IOException, URISyntaxException
{
new GooglePlacesClient().performSearch("establishment", 8.6668310, 50.1093060);
}
public void performSearch(final String types, final double lon, final double lat) throws ParseException, IOException, URISyntaxException
{
final URIBuilder builder = new URIBuilder().setScheme("https").setHost("maps.googleapis.com").setPath("/maps/api/place/search/json");
builder.addParameter("location", lat + "," + lon);
builder.addParameter("radius", "5");
builder.addParameter("types", types);
builder.addParameter("sensor", "true");
builder.addParameter("key", GooglePlacesClient.GOOGLE_API_KEY);
final HttpUriRequest request = new HttpGet(builder.build());
final HttpResponse execute = this.client.execute(request);
final String response = EntityUtils.toString(execute.getEntity());
System.out.println(response);
}
}
Here's a more complete example (includes JSON parsing and some exception handling) for Places API search, autocomplete, and details. It was written for Android, but can be easily ported for non-Android use (need to include org.json libs and use different logging). The Place class is a simple value object.
package com.example.google.places;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
/**
* #author saxman
*/
public class PlacesService {
private static final String LOG_TAG = "ExampleApp";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAILS = "/details";
private static final String TYPE_SEARCH = "/search";
private static final String OUT_JSON = "/json";
// KEY!
private static final String API_KEY = "YOUR KEY";
public static ArrayList<Place> autocomplete(String input) {
ArrayList<Place> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_AUTOCOMPLETE);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<Place>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
Place place = new Place();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("description");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
public static ArrayList<Place> search(String keyword, double lat, double lng, int radius) {
ArrayList<Place> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_SEARCH);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&keyword=" + URLEncoder.encode(keyword, "utf8"));
sb.append("&location=" + String.valueOf(lat) + "," + String.valueOf(lng));
sb.append("&radius=" + String.valueOf(radius));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("results");
// Extract the Place descriptions from the results
resultList = new ArrayList<Place>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
Place place = new Place();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("name");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
public static Place details(String reference) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_DETAILS);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&reference=" + URLEncoder.encode(reference, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return null;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
Place place = null;
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString()).getJSONObject("result");
place = new Place();
place.icon = jsonObj.getString("icon");
place.name = jsonObj.getString("name");
place.formatted_address = jsonObj.getString("formatted_address");
if (jsonObj.has("formatted_phone_number")) {
place.formatted_phone_number = jsonObj.getString("formatted_phone_number");
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return place;
}
}
A Java library for working with the Google Places API is available on GitHub and in Maven Central (disclosure: I'm the developer.) Getting a list of places (or details, photo, etc.) can be done in one or two lines. See the project page for examples and set up details.
https://github.com/pushbit/sprockets
There doesn't exist any official Java library available for Google Places API. However, there are several projects hosted on Github. Another one is this:
Google Places API Java Library on Github

Categories

Resources