So I get place_id by storing it in a Hashmap with the "name" of the place as the key.
private HashMap<String, String> placeTitleId = new HashMap<>();
if (!place.isNull("place_id")) {
placeId = place.getString("place_id");
placeTitleId.put(name, placeId);
}
Later, I create the Places Detail search url:
private String createPlaceDetailsUrl(String placeId) {
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?");
stringBuilder.append("placeid=").append(placeId);
stringBuilder.append("&key=").append(GOOGLE_PLACES_API_KEY);
return stringBuilder.toString();
}
Finally, I parse the json response:
JSONObject data = new JSONObject(result);
if (data.getString("status").equalsIgnoreCase("OK")) {
JSONArray photoArray = data.getJSONArray("photos");
}
What I don't understand is why the "photos" json array has no value
Android Monitor: W/System.err: org.json.JSONException: No value for photos
The documentation says that the photos[] jsonarray should have up to 10 photos. However, the json output schema does not contain a photos[] object, which I find weird. Is there a problem with how I am obtaining place_id or parsing the response?
EDIT:
The "result" String is incredibly long, but I can provide a gist:
result {
"address components" : [
*bunch of stuff*
]
...
"geometry" : {
*bunch of stuff*
}
"icon"
"id"
"photos" : [
{
"height"
"html_attributions:
"photo_reference!!
}
{
...
"photo_reference!!
}
*bunch more of these*
]
}
EDIT:
Fix is getting json object "result
JSONObject jsonObject = new JSONObject(result);
JSONObject data = new JSONObject("result");
The data object has "pictures"
Try this.
JSONObject data = new JSONObject(result);
// add log here ,make sure you have photos in your result
Log.e("result", result + "");
if (data.getString("status").equalsIgnoreCase("OK")) {
// edited here
JSONArray photoArray = data.optJSONArray("photos");
}
Edit
if (data .has("photos")) {
Log.e("photos", "photos exists");
} else {
Log.e("photos", "photos not exists");
}
Use data .has("photos") in your code and judge it .
Note
Use
JSONObject data = new JSONObject(result);
if(data.has("TAG")){
// if has it in your data,do something
}
to determine whether this tag is present in the data
I want to sort two json arrays stream and stream1 with respect to time together.
The record in each array with the latest time will come first.Time is formatted like value of min ago ,days ago
This is the code I have so far:
parseJsonFeed(JSONObject response) {
try {
String stream = pref.getStream();
JSONArray feedArray = response.getJSONArray(stream);
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("title"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilepic"));
item.setTimeStamp(feedObj.getString("created_at"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
String stream2 = pref.getStream2();
if (!stream2.contentEquals("none")) {
try {
JSONArray feedArray = response.getJSONArray(stream2);
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("title"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilepic"));
item.setTimeStamp(feedObj.getString("created_at"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I need to sort the arrays together to show the most recent item in each array first, then the next most recent, and so on.
Make the FeedItem class implement Comparable or Comparator (refer this). Then call :
Collections.sort(feedItem);
before calling notifyDataSetChanged()
I am trying retrieving the following JSON data from imagga's image recognition API.
{"results":[{"image":"http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg","tagging_id":null,"tags":[{"confidence":63.346307851163395,"tag":"valley"},{"confidence":60.66263009377379,"tag":"mountain"},{"confidence":44.39096006516168,"tag":"canyon"},{"confidence":42.08210930346856,"tag":"landscape"},{"confidence":33.52198895357515,"tag":"geological formation"},{"confidence":32.702112467737216,"tag":"mountains"},{"confidence":28.626223994488203,"tag":"glacier"},{"confidence":28.36,"tag":"natural depression"},{"confidence":28.03481906795487,"tag":"ravine"},{"confidence":27.269738461024804,"tag":"sky"},{"confidence":26.130797131953397,"tag":"rock"},{"confidence":23.11898739400327,"tag":"travel"},{"confidence":21.75182989551758,"tag":"alp"},{"confidence":20.956625061326214,"tag":"national"},{"confidence":20.15360199670358,"tag":"park"},{"confidence":19.826365024393702,"tag":"stone"},{"confidence":19.717420656127437,"tag":"water"},{"confidence":18.049071926896588,"tag":"river"},{"confidence":17.81629840041474,"tag":"hill"},{"confidence":17.30594970410163,"tag":"tourism"},{"confidence":17.192663177192692,"tag":"clouds"},{"confidence":16.53588724897844,"tag":"scenic"},{"confidence":15.98967256769248,"tag":"peak"},{"confidence":15.792599629554461,"tag":"lake"},{"confidence":15.532788988165363,"tag":"scenery"},{"confidence":15.453814687301834,"tag":"snow"},{"confidence":15.232632664896412,"tag":"outdoors"},{"confidence":15.212304004139495,"tag":"range"},{"confidence":15.042325772263556,"tag":"hiking"},{"confidence":14.958759294889424,"tag":"tree"},{"confidence":14.78842712696222,"tag":"forest"},{"confidence":12.853490785491731,"tag":"grass"},{"confidence":12.242518977753525,"tag":"desert"},{"confidence":12.095999999999998,"tag":"natural elevation"},{"confidence":12.03899501602295,"tag":"america"},{"confidence":11.49381779097963,"tag":"environment"},{"confidence":11.250534926394025,"tag":"usa"},{"confidence":10.935999552280517,"tag":"panorama"},{"confidence":10.838870815021957,"tag":"trees"},{"confidence":10.77081532273937,"tag":"south"},{"confidence":10.385222667460749,"tag":"summer"},{"confidence":9.967993711501377,"tag":"cloud"},{"confidence":9.960797892906747,"tag":"wild"},{"confidence":9.840206836878211,"tag":"natural"},{"confidence":9.64736797817423,"tag":"geology"},{"confidence":9.622992778171428,"tag":"rocky"},{"confidence":9.5011692563878,"tag":"outdoor"},{"confidence":9.36921935993258,"tag":"wilderness"},{"confidence":9.360136841263397,"tag":"vacation"},{"confidence":9.295849004816608,"tag":"rocks"},{"confidence":9.200756690906687,"tag":"high"},{"confidence":9.098263071652019,"tag":"highland"},{"confidence":8.912795414022,"tag":"tourist"},{"confidence":8.871604649828521,"tag":"hike"},{"confidence":8.849249986309006,"tag":"landmark"},{"confidence":8.696713373486205,"tag":"cliff"},{"confidence":8.600291951670297,"tag":"scene"},{"confidence":8.535889495009538,"tag":"stream"},{"confidence":8.530021520404471,"tag":"sunny"},{"confidence":8.255077489679804,"tag":"altitude"},{"confidence":8.016191292928964,"tag":"trail"},{"confidence":7.9938748285500605,"tag":"autumn"},{"confidence":7.985278417869093,"tag":"california"},{"confidence":7.927492176055299,"tag":"spain"},{"confidence":7.774043777890904,"tag":"adventure"},{"confidence":7.560207874392119,"tag":"peaceful"},{"confidence":7.485827508554503,"tag":"fall"},{"confidence":7.283862421876644,"tag":"erosion"},{"confidence":7.272123549182718,"tag":"terrain"},{"confidence":7.24510515635207,"tag":"rural"},{"confidence":7.234934522337296,"tag":"vista"},{"confidence":7.092282542389207,"tag":"holiday"}]}]}
I am using http://www.java2s.com/Code/Jar/o/Downloadorgjson20130603jar.htm library.
My Java code is as follows:
String imageUrl = "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg",
apiKey = "",
apiSecret = "";
// These code snippets use an open-source library. http://unirest.io/java
HttpResponse response = Unirest.get("https://api.imagga.com/v1/tagging")
.queryString("url", imageUrl)
.basicAuth(apiKey, apiSecret)
.header("Accept", "application/json")
.asJson();
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(response.getBody()); // json
System.out.print("hello");
JSONObject data1 = jObject.getJSONObject("results"); // get data
System.out.print(data1); // object
String projectname = data1.getString("tags"); // get the name
// from data.
System.out.print(projectname);
I am getting the error that
Exception in thread "main" org.json.JSONException:
JSONObject["results"] not found.
What I want to get is the list of "tag" and "confidence".
try this
JSONArray data1 = jObject.getJSONArray("results");
Edited Answer
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(js); // json
System.out.print("hello");
JSONArray data1 = jObject.getJSONArray("results");
for(int i = 0; i < data1.length; i++)
{
JSONObject jsonObject = data1.getJSONObject(i);
String projectn ame = jsonObject.getString("tagging_id");
System.out.print(projectname);
JSONArray tagArray = jsonObject.getJsonArray("tags");
for(int j = 0; j < tagArray.length; j++)
{
JSONObject tagObject = tagArray.getJSON(j);
System.out.println("Tag == " + tagObject.getString("tag"));
}
}
To make your life more easy I'd go to model the Objects as POJO's and let Jackson's Objectmapper do the magic.
See http://wiki.fasterxml.com/JacksonDataBinding
I suppose you should try jObject.getJSONArray("results") instead of jObject.getJSONObject("results").
There is also a good tool to convert json to java: http://json2java.azurewebsites.net/
If you use it, you will see:
...other code...
public class RootObject
{
private ArrayList<Result> results;
public ArrayList<Result> getResults() { return this.results; }
public void setResults(ArrayList<Result> results) { this.results = results; }
}
...other code...
And results is list here, so use getJSONArray instead of getJSONObject
If you look into your json results has an array in it and therefore you should use getJSONArray and not getJSONObject.
JSONArray data1 = jObject.getJSONArray("results");
Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, All code work till attachments how to get data from attachments I need to get "photo_75" from it
Json
"response":{
"count":3,
"items":[
{
"id":3,
"from_id":205110032,
"owner_id":-81865402,
"date":1417672154,
"post_type":"post",
"text":"jjjjASDFGHJKYTRDXCVB",
"attachments":[
{
"type":"photo",
"photo":{
"id":330414711,
"album_id":-7,
"owner_id":205110032,
"photo_75":"http:\/\/cs605116.vk.me\/v605116032\/6325\/3SwTo8j4lJ0.jpg",
"photo_130":"http:\/\/cs605116.vk.me\/v605116032\/6326\/_OZA86FO3Nw.jpg",
"photo_604":"http:\/\/cs605116.vk.me\/v605116032\/6327\/AUtB59708Nw.jpg",
"photo_807":"http:\/\/cs605116.vk.me\/v605116032\/6328\/59oAdfz9jgI.jpg",
"width":538,
"height":807,
"text":"",
"date":1399134687,
"access_key":"7297eb663de2e4e6b2"
}
}
],
"comments":{
"count":0
},
"likes":{
"count":0
},
"reposts":{
"count":0
}
},
Java
private void parseJsonFeed(JSONObject response) {
try {
JSONObject parent = response.getJSONObject("response");
JSONArray feedArray = parent.getJSONArray("items");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("post_type"));
item.setTimeStamp(feedObj.getString("date"));
// Image might be null sometimes
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
item.setStatus(feedObj.getString("text"));
All code work till there how to get data from attachments
***JSONObject response1 = response.getJSONObject("response");
feedArray = parent.getJSONArray("items");***
JSONArray feedArray1 = response1.getJSONArray("attachments");
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject feedObj1 = (JSONObject) feedArray1.get(i1);
FeedItem item1 = new FeedItem();
item.setProfilePic(feedObj1.getString("photo_75"));
}
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance
you are looking for attachments in wrong object. "attachmetnts" is property of item.
instead of
JSONArray feedArray1 = response1.getJSONArray("attachments");
use
JSONArray feedArray1 = feedObj.getJSONArray("attachments");
in your case feedObj contains item object.
to get photo :
Remove lines :
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
and change it to :
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject attachment = (JSONObject) feedArray1.get(i1);
JSONObject photo = (JSONObject) attachment.getJSONObject("photo");
item.setImge(photo);
item.setProfilePic(photo.getString("photo_75"));
item.setStatus(photo.getString("text"));
}
You can try GSON, which would directly give you a java object from your json and you would not have to parse it manually.
I have this JSON to parse
{"files_informations": {
"row":{"value":"artist1"},
"row":{"value":"artist2"}
}
}
I would like to know how can I get the first value artist1 and then the second one artist2
This is what I am doing :
JSONObject myObject = jObject.getJSONObject("files_informations");
JSONObject rowObject = myObject.getJSONObject("row");
Iterator<JSONObject> rowIt = rowObject.keys();
while (rowIt.hasNext()) {
JSONObject tmp = rowIt.next();
Log.e("", tmp.getString("value"));
}
I got java.lang.classCastException for this JSONObject tmp = rowIt.next();
So there are my two questions :
Do I need to use iterators in this
case ?
How do one should use them ?
Edit :
Should the JSON looks like this ?
{"files_informations": [
"row":{"value":"artist2"},
"row":{"value":"artist1"}
]
}
rowIt.next() is "row" String in this case.
Refactor your JSON to this:
{"files_informations":
[ {"value":"artist2"},
{"value":"artist1"} ] }
Or even this:
{ "files_informations": [ "artist2", "artist1" ] }
and then use:
JSONArray artistsArr = myObject.getJSONArray("files_informations");
for (int i = 0; i < artistsArr.size(); i++) {
// first case
Log.d(TAG, artistsArr.get(i).getString("value"));
// Second case
Log.d(TAG, artistsArr.getString(i));
}
Iterators are not supported in JSONArrays, however you can convert them to plain Java arrays/lists if you really need it.