Reputation: 323
I know this could have been asked, but I couldn't get a specific answer. I have a json String:
GraphObject{graphObjectClass=GraphPlace, state={"id":"268367713308665","category":"School","location":{"state":"","zip":"","longitude":32.631482614136,"latitude":0.24519375867929,"country":"Uganda","city":"Kampala","street":"PO BOX 28493"},"category_list":[{"id":"365182493518892","name":"School"}],"name":"Little Wonders Montessori"}}
GraphObject{graphObjectClass=GraphPlace, state={"id":"142442605900768","category":"Education","location":{"state":"","zip":"","longitude":32.606752647018,"latitude":0.28746491511647,"country":"Uganda","city":"Kampala","street":"Heritage\/ Kiwafu Stage, Wheeling Zone, Gaba Road, Kansanga"},"category_list":[{"id":"151676848220295","name":"Education"}],"name":"Wisdomgate Pre-School, Kansanga."}}
which I'm getting from facebook when I query for nearby places, and I would like to extract the latitude, longitude, category and name. This is what am trying
public void onCompleted(List<GraphPlace> places, Response response) {
//Toast.makeText(getActivity(), (CharSequence) places.listIterator(), Toast.LENGTH_LONG).show();
ListIterator<GraphPlace> x = places.listIterator();
while(x.hasNext()){
String f = x.next().toString();
Toast.makeText(getActivity(), f, Toast.LENGTH_LONG).show();
mytext.setText(f);
try {
JSONObject json = new JSONObject(f);
JSONArray array = json.getJSONArray( "GraphPlace" );
Toast.makeText(getActivity(), array.length(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
request.executeAsync();
However, I can't seem to get an entry point, and however much I try, I can't get anything Thanks for the help in advance.
Upvotes: 1
Views: 5653
Reputation: 23503
If your JSON string looks like this:
{"id":"268367713308665","category":"School","location":{"state":"","zip":"","longitude":32.631482614136,"latitude":0.24519375867929,"country":"Uganda","city":"Kampala","street":"PO BOX 28493"},"category_list":[{"id":"365182493518892","name":"School"}],"name":"Little Wonders Montessori"}}
To get latitude and longitude would be:
JSONObject json = new JSONObject(yourJSONVariableHere);
JSONObject location = json.getJSONObject( "Location" );
String lat = location.getString("latitude");
String long = location.getString("longitude");
For the lat
and long
variables, you can assign int
or long
depending on the value of the JSON. If you change the variable type, you would do getInt()
or getLong
for the respective variable value.
The other things to keep in mind is that you have a nested object, which holds the lat
and long
, so you have to get that, then parse that. The same goes if you have nested arrays, or other objects. Currently you are using getJSONArray
, but arrays in JSON have [array, array]
, or square brackets, where JSON objects have {object, object}
curly braces.
Hope this helps.
Upvotes: 1