This is the function that's giving me the problem:
public String URLToJson() {
String result = "";
String jsonString = ReadingURL(" here goes my URL that reads a JSON ");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
JSONArray data = jsonResult.getJSONArray("Configuracion");
if (data != null) {
for (int i = 0; i <= data.length(); i++) {
result = result + "Dirección: " + data.getJSONObject(i).getString("Direccion") + "\n";
result = result + "Cédula: " + data.getJSONObject(i).getString("Cedula") + "\n";
result = result + "Nombre: : " + data.getJSONObject(i).getString("Nombre") + "\n";
result = result + "Teléfono : " + data.getJSONObject(i).getString("Telefono") + "\n";
result = result + "Hacienda: " + data.getJSONObject(i).getString("Hacienda") + "\n";
}
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And then this comes up:
`W/System.err: org.json.JSONException: Value {"Direccion":"Somewhere","Cedula":"111111","Nombre":"Something","Telefono":"2222-2440","Hacienda":"Something"} at Configuracion of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:588)
at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:977)
W/System.err: at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)W/System.err: org.json.JSONException: Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray`
ReadingURL basically reads the content of an URL, that has the JSON in String.
From the exception it's clear that the JSON string returned by the URL is of type JSONObject not of JSONArray .
Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray
JSON object will starts with { & ends with }
{
"KEY1":"VALUE1",
"KEY2":"VALUE2"
}
and JSON array will starts with [ and ends with ] .
[
{"KEY1":"VALUE1","KEY2":"VALUE2"},{"KEY1":"VALUE1","KEY2":"VALUE2"}
]
So you are getting this exception because you are trying to convert JSON object to JSON array.
to Deepak Gunasekaran
public String URLToJson() {
String result = "";
String jsonString = ReadingURL("http://deliciasmarinas.avancari.co.cr/app/tiquete.php?factura=414696772");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
for (int i = 0; i <= jsonResult.length(); i++) {
result = result + "Dirección: " + jsonResult.get("Direccion") + "\n";
result = result + "Cédula: " + jsonResult.get("Cedula") + "\n";
result = result + "Nombre: : " + jsonResult.get("Nombre") + "\n";
result = result + "Teléfono : " + jsonResult.get("Telefono") + "\n";
result = result + "Hacienda: " + jsonResult.get("Hacienda") + "\n";
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And now it just shows
W/System.err: org.json.JSONException: No value for Direccion
at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:978)
at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)
Related
I'm new in Volley JSONArray. I unable to setText in txtResponse because I always getting this error at onErrorResponse.
This is my Logcat
......com.example.simplevolley.simplevolley W/System.err: org.json.JSONException: Value [{"com_branch_id":7,"com_branch_comId":1,"com_branch_name":"JT Temerloh","com_branch_manager":"Tn Hj Ahmad Bin Hj Mohd Sidin","com_branch_addr":"No.58, Jalan Ibrahim (Jln Masjid Abu Bakar)","com_branch_region":"Temerloh","com_branch_state":"PAHANG","com_branch_country":"MALAYSIA","com_branch_poscode":"28000","com_branch_email":"tmlh#juaratravel.com.my","com_branch_licence":null,"com_branch_phoneNum":"09-2965625","com_branch_fax":null,"com_branch_fb":null,"com_branch_ig":null},{"com_branch_id":9,"com_branch_comId":1,"com_branch_name":"JT Nibong Tebal","com_branch_manager":"Pejabat Penang","com_branch_addr":"No. 10, Tingkat Atas, Jln Pekaka 1, Tmn Pekaka,","com_branch_region":"Nibong Tebal","com_branch_state":"PULAU PINANG","com_branch_country":"MALAYSIA","com_branch_poscode":"14300","com_branch_email":"pen#juaratravel.com.my","com_branch_licence":null,"com_branch_phoneNum":"05-7171877","com_branch_fax":"057161877","com_branch_fb":null,"com_branch_ig":null}......
I want to read this JSON lines but because it start with JSONArray I'm so confused.
{
"res": true,
"datas": [
{
"com_branch_id": 7,
"com_branch_comId": 1,
"com_branch_name": "JT Temerloh",
"com_branch_manager": "Tn Hj Ahmad Bin Hj Mohd Sidin",
"com_branch_addr": "No.58, Jalan Ibrahim (Jln Masjid Abu Bakar)",
"com_branch_region": "Temerloh",
"com_branch_state": "PAHANG",
"com_branch_country": "MALAYSIA",
"com_branch_poscode": "28000",
"com_branch_email": "tmlh#juaratravel.com.my",
"com_branch_licence": null,
"com_branch_phoneNum": "09-2965625",
"com_branch_fax": null,
"com_branch_fb": null,
"com_branch_ig": null
},
{
"com_branch_id": 9,
"com_branch_comId": 1,
"com_branch_name": "JT Nibong Tebal",
"com_branch_manager": "Pejabat Penang",
"com_branch_addr": "No. 10, Tingkat Atas, Jln Pekaka 1, Tmn Pekaka,",
"com_branch_region": "Nibong Tebal",
"com_branch_state": "PULAU PINANG",
"com_branch_country": "MALAYSIA",
"com_branch_poscode": "14300",
"com_branch_email": "pen#juaratravel.com.my",
"com_branch_licence": null,
"com_branch_phoneNum": "05-7171877",
"com_branch_fax": "057161877",
"com_branch_fb": null,
"com_branch_ig": null
},]}
I need to get all datas value. This is my code
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("res", response.toString());
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject branchi = (JSONObject) response.get(i);
JSONObject branch = branchi.getJSONObject("datas");
Integer com_branch_id = Integer.valueOf(branch.getString("com_branch_id"));
Integer com_branch_comId = Integer.valueOf(branch.getString("com_branch_comId"));
String com_branch_name = branch.getString("com_branch_name");
String com_branch_manager = branch.getString("com_branch_manager");
String com_branch_addr = branch.getString("com_branch_addr");
String com_branch_region = branch.getString("com_branch_region");
String com_branch_state = branch.getString("com_branch_state");
String com_branch_country = branch.getString("com_branch_country");
String com_branch_poscode = branch.getString("com_branch_poscode");
String com_branch_email = branch.getString("com_branch_email");
String com_branch_licence = branch.getString("com_branch_licence");
String com_branch_phoneNum = branch.getString("com_branch_phoneNum");
String com_branch_fax = branch.getString("datas.com_branch_fax");
String com_branch_fb = branch.getString("datas.com_branch_fb");
String com_branch_ig = branch.getString("datas.com_branch_ig");
jsonResponse = "";
jsonResponse += "Branch name: " + com_branch_id + "\n\n";
jsonResponse += "Branch manager: " + com_branch_comId + "\n\n";
jsonResponse += "Branch state: " + com_branch_name + "\n\n";
jsonResponse += "Branch state: " + com_branch_manager + "\n\n";
jsonResponse += "Branch state: " + com_branch_addr + "\n\n";
jsonResponse += "Branch state: " + com_branch_region + "\n\n";
jsonResponse += "Branch state: " + com_branch_state + "\n\n";
jsonResponse += "Branch state: " + com_branch_country + "\n\n";
jsonResponse += "Branch state: " + com_branch_poscode + "\n\n";
jsonResponse += "Branch state: " + com_branch_email + "\n\n";
jsonResponse += "Branch state: " + com_branch_licence + "\n\n";
jsonResponse += "Branch state: " + com_branch_phoneNum + "\n\n";
jsonResponse += "Branch state: " + com_branch_fax + "\n\n";
jsonResponse += "Branch state: " + com_branch_fb + "\n\n";
jsonResponse += "Branch state: " + com_branch_ig + "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"res" + e.getMessage(),
Toast.LENGTH_LONG).show();
txtResponse.setText(e.getMessage());
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "res" + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
Log.d("onErrorResponse", error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
I try to follow other solution but unfortunately I fail and stuck.
try this..
JSONObject json = new JSONObject(response);
JSONArray jsonarray = json.getJSONArray("datas");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = jsonarray.getJSONObject(i);
//here you get by json key
String id = c.getString("com_branch_id");
}
1) Your Json is not an array(it starts with { implying an object
json). Use JsonObjectRequest.
2) Rather than grabbing the elements,
in your response, by iterating you can use a jackson2 to map the
response to your POJO.
3) You can use jsonschema2pojo to create a
POJO class
JsonArrayRequest will give you response as JSONArray. But your response is not JSONArray. Its JSONObject and that JSONObject contains JSONArray.
Use JsonObjectRequest for your case.
You can use Gson to convert you response to Java object.
Make a Java Pojo class that match with your response format. Than convert your response into java object.
public void onResponse(JSONObject response) {
String message = "";
if (response != null) {
message = response.toString();
Post post = null;
Gson gson = new Gson();
post = gson.fromJson(response.toString(), Post.class);
} else {
message = "Response is null";
}
}
I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
How can I deserialize this complex JSON .
I want to access all objects and read.
For example SelectionId and AdditionalPriceInfo fields by indexing.
get(0).getSelectionId() --> d51d38c9-6e51-473c-b843-f24fef632f89
{
"Status": 0,
"Message": "",
"Result": {
"HasMore": "False",
"Itineraries": [
{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "02:00:00"
}
]
},
{
"SelectionId": "ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "01:23:00"
}
]
}
],
"SearchOriginCityText": "Long Beach",
"SearchOriginAirportCode": "LGB",
"SearchDestinationCityText": "SFO",
"SearchDestinationAirportCode": "SFO"
}
}
My code so far for accessing all I want:
Gson gson2 = new Gson();
AirJson airJson = gson2.fromJson(airFullResult3, AirJson.class);
Itineraries itineraries = gson2.fromJson(airFullResult3, Itineraries.class);
Result result = gson2.fromJson(airFullResult3, Result.class);
//Having null instead SFO
System.out.println(result.getSearchDestinationAirportCode());
//Having null
System.out.println(itineraries.getAdditionalPriceInfo());
When I split my JSON, I can access the values that I want.
{
"Itineraries": [{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null
}, {
"SelectionId": "dda40b80-d8e4-4b76-9f78-83297b52afe9",
"AdditionalPriceInfo": null
}]
}
Successful code and I access values.
JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(airFullResult).getAsJsonObject();
JsonElement projectElement = rootObject.get("Itineraries");
Type listofObject = new TypeToken<List<Itineraries>>(){}.getType();
List<Itineraries> itiList = gson2.fromJson(projectElement, listofObject);
//Having d51d38c9-6e51-473c-b843-f24fef632f89 as a result
//which is great
System.out.println(itiList.get(0).getSelectionId());
When I use the same code for first unallocated JSON, doesn't work and having java.lang.NullPointerException as error
you need to build one object with a couple of child objects which represents your json-structure. the following code works! (testet with java 8, and gson 2.6.2)
#Test
public void test() {
Gson gson = new Gson();
Data data = gson.fromJson(getJson(), Data.class);
Assert.assertNotNull(data);
Assert.assertNotNull(data.result);
Assert.assertNotNull(data.result.itineraries);
Assert.assertEquals(2, data.result.itineraries.length);
Assert.assertEquals("d51d38c9-6e51-473c-b843-f24fef632f89", data.result.itineraries[0].selectionId);
Assert.assertEquals("ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c", data.result.itineraries[1].selectionId);
}
public class Data {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("HasMore")
String hasMore;
#SerializedName("Itineraries")
Itineraries[] itineraries;
#SerializedName("SearchOriginCityText")
String searchOriginCityText;
#SerializedName("SearchOriginAirportCode")
String searchOriginAirportCode;
#SerializedName("SearchDestinationCityText")
String searchDestinationCityText;
#SerializedName("SearchDestinationAirportCode")
String searchDestinationAirportCode;
}
public class Itineraries {
#SerializedName("SelectionId")
String selectionId;
#SerializedName("AdditionalPriceInfo")
String additionalPriceInfo;
#SerializedName("Trips")
Trips[] trips;
}
public class Trips {
#SerializedName("TotalTravelTime")
String totalTravelTime;
}
private String getJson() {
String json = "";
json += "{";
json += " \"Status\": 0,";
json += " \"Message\": \"\",";
json += " \"Result\": {";
json += " \"HasMore\": \"False\",";
json += " \"Itineraries\": [";
json += " {";
json += " \"SelectionId\": \"d51d38c9-6e51-473c-b843-f24fef632f89\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"02:00:00\"";
json += " }";
json += " ]";
json += " },";
json += " {";
json += " \"SelectionId\": \"ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"01:23:00\"";
json += " }";
json += " ]";
json += " }";
json += " ],";
json += " \"SearchOriginCityText\": \"Long Beach\",";
json += " \"SearchOriginAirportCode\": \"LGB\",";
json += " \"SearchDestinationCityText\": \"SFO\",";
json += " \"SearchDestinationAirportCode\": \"SFO\"";
json += " }";
json += "}";
return json;
}
How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.
I'm currently working on a project that requires the latitude and longitude of a given address (input). Google maps API returns in json format, and I've done research and found that json-simple is the best option for my project. I have this code as well as the String output from google maps API, and would highly appreciate some help in parsing properly.
Also note: the call: MapTile.receiveJson just returns the string from google's API (linked below)
try {
String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonAdr);
System.out.println("lat=" + json.get("address_components"));
} catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}
This is the exact string output from google's API:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
I realize I could do String parsing, however it would be inefficient as I will be using more of google's API. I have also viewed other stack overflow, as well as their JSON website but found no examples with multiple JSON arrays such as those returned by google.
Any help is greatly appreciated.
Here's the solution:
I basically made a stand alone and I parsed your JSON like this:
First : This is the method I used to parse the JSON:
public String loadJSON(String someURL) {
String json = null;
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(someURL);
try {
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
StatusLine statusline = mHttpResponse.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode != 200) {
return null;
}
InputStream jsonStream = mHttpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = builder.toString();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
mHttpClient.getConnectionManager().shutdown();
return json;
}
Second : Used Async Task to download the data:
public class BackTask extends AsyncTask<Void, Void, Void> {
String url;
public BackTask(String URL) {
super();
this.url = URL;
}
#Override
protected Void doInBackground(Void... params) {
getData(url);
return null;
}
}
Third: Method to get the data and parse it. I have made some comments for this part since it's a bit long than usual.
public void getData(String URL) {
try {
JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
// Log.d("JSON Data : ", mainJsonObject.toString());
String Status = mainJsonObject.getString("status");
Log.d("JSON Status : ", Status + "\n" + "---------------------");
JSONArray mainArray = mainJsonObject.getJSONArray("results");
// Log.d("JSON Array : ", mainArray.toString());
for (int i = 0; i < mainArray.length(); i++) {
JSONObject insideJsonObject = mainArray.getJSONObject(i);
if (insideJsonObject != null) {
String address_components = insideJsonObject
.getString("address_components");
// Log.d("Inside JSON Array : ", address_components);
JSONArray addressJSON = insideJsonObject
.getJSONArray("address_components");
// Log.d("Inside JSON ADDress : ", addressJSON.toString());
String formatted_address = insideJsonObject
.getString("formatted_address");
Log.d("Inside JSON formatted_address : ", formatted_address
+ "\n" + "-----------");
for (int ji = 0; ji < mainArray.length(); ji++) {
JSONObject geoMetryJO = mainArray.getJSONObject(ji);
if (geoMetryJO != null) {
JSONObject geometry = geoMetryJO
.getJSONObject("geometry");
// Log.d("Inside JSON geometry : ",
// geometry.toString()+"\n"+"----------");
String location_type = geometry
.getString("location_type");
Log.d("Inside JSON location_type : ", location_type
+ "\n" + "------------");
JSONObject locationJSONObject = geometry
.getJSONObject("location");
String Latitude = locationJSONObject
.getString("lat");
Log.d("Inside JSON Latitude : ", Latitude + "\n"
+ "--------------");
String Longitude = locationJSONObject
.getString("lng");
Log.d("Inside JSON Longitude : ", Longitude + "\n"
+ "------------");
JSONObject viewportJSONObject = geometry
.getJSONObject("viewport");
// Log.d("Inside JSON viewportJSONObject : ",
// viewportJSONObject.toString()+"\n"+"------------");
JSONObject northeastJSONObject = viewportJSONObject
.getJSONObject("northeast");
String Lat = northeastJSONObject.getString("lat");
Log.d("Inside JSON Lat : ", Lat + "\n"
+ "------------");
String Lon = northeastJSONObject.getString("lng");
Log.d("Inside JSON Lon : ", Lon + "\n"
+ "------------");
JSONObject southwestJSONObject = viewportJSONObject
.getJSONObject("southwest");
String south_Lat = southwestJSONObject
.getString("lat");
Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
+ "------------");
String south_Lon = southwestJSONObject
.getString("lng");
Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
+ "------------");
}
}
for (int k = 0; k < addressJSON.length(); k++) {
JSONObject addressJSONObject = addressJSON
.getJSONObject(k);
if (addressJSONObject != null) {
String long_name = addressJSONObject
.getString("long_name");
Log.d("Inside JSON LongName : ", long_name);
String short_name = addressJSONObject
.getString("short_name");
Log.d("Inside JSON ShortName : ", short_name);
JSONArray addressJSONArray = addressJSONObject
.getJSONArray("types");
Log.d("Inside JSON JSONADD : ",
addressJSONArray.toString() + "\n"
+ "-------------");
}
}
JSONArray insideJsonArray = insideJsonObject
.getJSONArray("types");
Log.d("Inside JSON Types : ", insideJsonArray.toString());
String street = insideJsonObject.getString("types");
Log.d("Inside JSON Street : ", street);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After getting all the data, you can use it in anyway you want cause it's mostly in the string format. You can just copy and paste this method and it should run fine.
Fourth : On the onCreate() method, just executed the task like this:
public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackTask(URL).execute();
}
This was the complete solution for this question. Let me know if have any questions for this. Hope this helps..Good Luck.. :)
I did this for formatted_address. I type casted explicitly here. But getJSONArray () and getJSONObject() methods will perform the typecasting too.
// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++)
System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.