Formatting JSON response - java

This is the JSON response I am getting using Foursquare API. Here, I am able to extract names of different venues using "name" tag and display as listview. But, the issue is I am not able to extract data from "location" tag given in JSON response.
This is how I am getting names of venues:
jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
// products found
// Getting Array of Products
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
// looping through All Products
for (int i = 0; i < cinemas.length(); i++) {
JSONObject venueObject = cinemas.getJSONObject(i);
// String id = venueObject.getString(TAG_PID);
String name = venueObject.getString(TAG_NAME);
prgmName.add(name);
}
JSON response:
{
"response": {
"venues": [
{
"referralId": "v1404154392",
"id": "52cd70b711d279a93b2761ac",
"location": {
"formattedAddress": [
"",
"India"
],
"distance": 635,
"lng": 70.79618019123747,
"cc": "IN",
"lat": 22.302471281197825,
"country": "India"
},
"stats": {
"checkinsCount": 24,
"tipCount": 0,
"usersCount": 14
},
"verified": false,
"name": "R WORLD BIG CINEMA",
"categories": [
{
"id": "4bf58dd8d48988d180941735",
"icon": {
"suffix": ".png",
"prefix": "https://ss1.4sqi.net/img/categories_v2/arts_entertainment/movietheater_"
},
"shortName": "Cineplex",
"pluralName": "Multiplexes",
"primary": true,
"name": "Multiplex"
}
],
"hereNow": {
"summary": "0 people here",
"count": 0,
"groups": []
},
"contact": {},
"specials": {
"count": 0,
"items": []
}
}
]
},
"meta": {
"code": 200
}
}
Any help in this regard will be great.

try {
objMain = new JSONObject(response);
JSONObject objRes=objMain.getJSONObject("response");
JSONArray arrVenues=objRes.getJSONArray("venues");
JSONObject obj=arrVenues.getJSONObject(0);
JSONObject objLocation=obj.getJSONObject("location");
Double lat=objLocation.getDouble("lat");
Double lnt=objLocation.getDouble("lng");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You can use getJSONObject again onvenueObject`:
Try this for example:
jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
// products found
// Getting Array of Products
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
// looping through All Products
for (int i = 0; i < cinemas.length(); i++) {
JSONObject venueObject = cinemas.getJSONObject(i);
String name = venueObject.getString(TAG_NAME);
JSONObject location = venueObject. getJSONObject(TAG_LOCATION);
String countryCode = location.getString("cc");
prgmName.add(name);
}

location is an json object again in the results array so you have to modify your code:-
for (int i = 0; i < cinemas.length(); i++)
{
JSONObject venueObject = cinemas.getJSONObject(i);
String name = venueObject.getString(TAG_NAME);
JSONObject find_location=venueObject.getJSONObject("location");
String lat = find_location.getString("lat");
String lon = find_location.getString("lng");
prgmName.add(name);
}

jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
for (int i = 0; i < cinemas.length(); i++)
{
JSONObject venue = cinemas.getJSONObject(i);
String name = venue.getString(TAG_NAME);
JSONObject loc = venue. getJSONObject(TAG_LOCATION);
String countryCode = location.getString(3);
String lat = loc.getString("lat");
String lon = loc.getString("lng");
prgmName.add(name);
}

Try this way,hope this will help you to solve your problem.
String jsonStr ="{\"response\":{\"venues\":[{\"referralId\":\"v1404154392\",\"id\":\"52cd70b711d279a93b2761ac\",\"location\":{\"formattedAddress\":[\"\",\"India\"],\"distance\":635,\"lng\":70.79618019123747,\"cc\":\"IN\",\"lat\":22.302471281197825,\"country\":\"India\"},\"stats\":{\"checkinsCount\":24,\"tipCount\":0,\"usersCount\":14},\"verified\":false,\"name\":\"R WORLD BIG CINEMA\",\"categories\":[{\"id\":\"4bf58dd8d48988d180941735\",\"icon\":{\"suffix\":\".png\",\"prefix\":\"https:\\/\\/ss1.4sqi.net\\/img\\/categories_v2\\/arts_entertainment\\/movietheater_\"},\"shortName\":\"Cineplex\",\"pluralName\":\"Multiplexes\",\"primary\":true,\"name\":\"Multiplex\"}],\"hereNow\":{\"summary\":\"0 people here\",\"count\":0,\"groups\":[]},\"contact\":{},\"specials\":{\"count\":0,\"items\":[]}}]},\"meta\":{\"code\":200}}";
try {
JSONObject respone = new JSONObject(jsonStr);
String code = respone.getJSONObject("meta").getString("code");
JSONArray jsonArr = respone.getJSONObject("response").getJSONArray("venues");
ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < jsonArr.length(); i++) {
HashMap<String, Object> venueMap = new HashMap<String, Object>();
venueMap.put("referralId", jsonArr.getJSONObject(i).getString("referralId"));
venueMap.put("id", jsonArr.getJSONObject(i).getString("id"));
venueMap.put("verified", jsonArr.getJSONObject(i).getString("verified"));
venueMap.put("name", jsonArr.getJSONObject(i).getString("name"));
HashMap<String,Object> locationMap = new HashMap<String, Object>();
locationMap.put("distance", jsonArr.getJSONObject(i).getJSONObject("location").getString("distance"));
locationMap.put("lng", jsonArr.getJSONObject(i).getJSONObject("location").getString("lng"));
locationMap.put("cc", jsonArr.getJSONObject(i).getJSONObject("location").getString("cc"));
locationMap.put("lat", jsonArr.getJSONObject(i).getJSONObject("location").getString("lat"));
locationMap.put("country", jsonArr.getJSONObject(i).getJSONObject("location").getString("country"));
ArrayList<String> formattedAddressList = new ArrayList<String>();
JSONArray formattedAddressJsonArray = jsonArr.getJSONObject(i).getJSONObject("location").getJSONArray("formattedAddress");
for(int j=0;j<formattedAddressJsonArray.length();j++){
formattedAddressList.add(formattedAddressJsonArray.getString(j));
}
locationMap.put("formattedAddress",formattedAddressList);
venueMap.put("location",locationMap);
HashMap<String,Object> statsMap = new HashMap<String, Object>();
statsMap.put("distance", jsonArr.getJSONObject(i).getJSONObject("stats").getString("checkinsCount"));
statsMap.put("tipCount", jsonArr.getJSONObject(i).getJSONObject("stats").getString("tipCount"));
statsMap.put("usersCount", jsonArr.getJSONObject(i).getJSONObject("stats").getString("usersCount"));
venueMap.put("stats",statsMap);
ArrayList<HashMap<String,Object>> categoriesList = new ArrayList<HashMap<String, Object>>();
JSONArray categoriesJsonArray = jsonArr.getJSONObject(i).getJSONArray("categories");
for(int j=0;j<categoriesJsonArray.length();j++) {
HashMap<String, Object> categoryMap = new HashMap<String, Object>();
categoryMap.put("id", categoriesJsonArray.getJSONObject(j).getString("id"));
categoryMap.put("shortName", categoriesJsonArray.getJSONObject(j).getString("shortName"));
HashMap<String,String> iconMap = new HashMap<String, String>();
iconMap.put("suffix", categoriesJsonArray.getJSONObject(j).getJSONObject("icon").getString("suffix"));
iconMap.put("prefix", categoriesJsonArray.getJSONObject(j).getJSONObject("icon").getString("prefix"));
categoryMap.put("icon", iconMap);
categoryMap.put("pluralName", categoriesJsonArray.getJSONObject(j).getString("pluralName"));
categoryMap.put("primary", categoriesJsonArray.getJSONObject(j).getString("primary"));
categoryMap.put("name", categoriesJsonArray.getJSONObject(j).getString("name"));
categoriesList.add(categoryMap);
}
venueMap.put("categories",categoriesList);
HashMap<String,Object> hereNowMap = new HashMap<String, Object>();
hereNowMap.put("summary", jsonArr.getJSONObject(i).getJSONObject("hereNow").getString("summary"));
hereNowMap.put("count", jsonArr.getJSONObject(i).getJSONObject("hereNow").getString("count"));
ArrayList<String> groupsList = new ArrayList<String>();
JSONArray groupsJsonArray = jsonArr.getJSONObject(i).getJSONObject("hereNow").getJSONArray("groups");
for(int j=0;j<groupsJsonArray.length();j++){
groupsList.add(groupsJsonArray.getString(j));
}
hereNowMap.put("groups",groupsList);
venueMap.put("hereNow",hereNowMap);
JSONObject contact = jsonArr.getJSONObject(i).getJSONObject("contact");
HashMap<String,Object> specialsMap = new HashMap<String, Object>();
specialsMap.put("count", jsonArr.getJSONObject(i).getJSONObject("specials").getString("count"));
ArrayList<String> itemsList = new ArrayList<String>();
JSONArray itemsJsonArray = jsonArr.getJSONObject(i).getJSONObject("specials").getJSONArray("items");
for(int j=0;j<itemsJsonArray.length();j++){
itemsList.add(itemsJsonArray.getString(j));
}
specialsMap.put("items",itemsList);
venueMap.put("specials",specialsMap);
list.add(venueMap);
}
System.out.print("Code: " + code);
for (HashMap<String,Object> venue : list){
System.out.print("referralId : " + venue.get("referralId"));
System.out.print("id : " + venue.get("id"));
System.out.print("verified : " + venue.get("verified"));
System.out.print("name : " + venue.get("name"));
HashMap<String,Object> locationMap = (HashMap<String,Object>)venue.get("location");
System.out.print("distance : " + locationMap.get("distance"));
System.out.print("lng : " + locationMap.get("lng"));
System.out.print("cc : " + locationMap.get("cc"));
System.out.print("lat : " + locationMap.get("lat"));
System.out.print("country : " + locationMap.get("country"));
ArrayList<String> formattedAddressList = (ArrayList<String>) locationMap.get("formattedAddress");
for (String formattedAddress : formattedAddressList){
System.out.print("formattedAddress : " +formattedAddress);
}
HashMap<String,Object> statsMap = (HashMap<String,Object>)venue.get("stats");
System.out.print("distance : " + statsMap.get("distance"));
System.out.print("tipCount : " + statsMap.get("lng"));
System.out.print("usersCount : " + statsMap.get("cc"));
ArrayList<HashMap<String,Object>> categoriesList = (ArrayList<HashMap<String,Object>>)venue.get("categories");
for (HashMap<String,Object> category : categoriesList){
System.out.print("id : " + category.get("id"));
System.out.print("shortName : " + category.get("shortName"));
System.out.print("shortName : " + category.get("shortName"));
HashMap<String,Object> icon = (HashMap<String,Object>)category.get("icon");
System.out.print("icon suffix: " + icon.get("suffix"));
System.out.print("icon prefix: " + icon.get("prefix"));
System.out.print("pluralName : " + category.get("pluralName"));
System.out.print("primary : " + category.get("primary"));
System.out.print("name : " + category.get("name"));
}
HashMap<String,Object> hereNowMap = (HashMap<String,Object>)venue.get("hereNow");
System.out.print("summary : " + hereNowMap.get("summary"));
System.out.print("count : " + hereNowMap.get("count"));
ArrayList<String> groupsList = (ArrayList<String>) hereNowMap.get("groups");
for (String group : groupsList){
System.out.print("group : " +group);
}
HashMap<String,Object> specialsMap = (HashMap<String,Object>)venue.get("specials");
System.out.print("count : " + specialsMap.get("summary"));
ArrayList<String> itemsList = (ArrayList<String>) specialsMap.get("items");
for (String item : itemsList){
System.out.print("item : " +item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to read an array inside an array inside an array from a volley response?

I'm using volley to make a request to the server, the server respond with a multidimensional array,
and i'm trying to read the "second" array "details" that are inside one show;
This is what im using to read the response:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Shows");
Log.e(TAG, "Response Array: " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
} catch (JSONException e) {
e.printStackTrace();
}
}
I tryed doing whit inside the loop, but it did'n work :/
JSONArray arr = new JSONArray(jsonArray);
for (int e = 0; e < arr.length(); e++) {
Log.e(TAG, "INSIDE");
}
"Shows" : [
{
"details" : [
"id" : 23adda,
"date" : "Monday",
"time" : "5:00PM"
"details: [
"Address" : "123 street";
"City" : "Test"
]
],
"id" : 15sdsd,
"Heading" : "The Big Show",
"Category" : "Family show",
"AssetId" : 8c8be292,
}
{
"details" : [
"id" : 23adda,
"date" : "Monday",
"time" : "5:00PM"
],
"id" : 15sdsd,
"Heading" : "The Big Show",
"Category" : "Family show",
"AssetId" : 8c8be292,
}
]
You can try below code :
JSONArray jsonArray = response.getJSONArray("Shows");//getting array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject= jsonArray.getJSONObject(i);//getting first element
String id= jsonobject.getString("id");//getting id
String Heading= jsonobject.getString("Heading");//getting Heading
String Category= jsonobject.getString("Category");//getting Category
String AssetId= jsonobject.getString("AssetId");//getting AssetId
System.out.println(""+id+""+Heading+""+AssetId+""+Category) ;
JSONArray jsonObject1= jsonobject.getJSONArray("details"); //getting children array
for (int j = 0; j < jsonObject1.length(); j++) {
JSONObject object1 = jsonObject1.getJSONObject(j);
String id1= object1.getString("id");//getting id
String date= object1.getString("date");//getting date
String time= object1.getString("time");//getting time
System.out.println(""+id1+""+City+""+time) ;
JSONArray jsonObject2= object1.getJSONArray("details"); //getting children array
for (int k = 0; k < jsonObject2.length(); k++) {
JSONObject object2 = jsonObject2.getJSONObject(k);
String Address= object2.getString("Address");//getting Address
String City= object2.getString("City");//getting City
System.out.println(""+Address+""+City) ;
}
}
}

Convert JSON Object as a Flat Obejct with Key value pair

I am getting a JSON object which looks like:
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
{
"items": [{
"id": "1"
}]
}
}
I want to represent this as flat map, but I want to represent the array of items as a list.
My output should look like:
{
"id": "1",
"name":"Hw",
"price":"10",
"items": ["1"]
}
Can anybody suggest me how I can achieve this? I tried this approach:
How to deserialize JSON into flat, Map-like structure?
Output from the above tried link:
{
"id": "1",
"name":"Hw",
"price.value":"10",
"items[0].id": "1"
}
But it is representing the arrays values as array[0], array[1] which I don't need. I need this array as a list.
The JSON you've given is not valid. I assume it's:
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [{
"id": "1"
}]
}
There cannot be a generic solution to what you're asking. But for this particular JSON, this will do(using json-simple):
#SuppressWarnings("unchecked")
public Map<String, String> transform(String inputJSON) throws ParseException {
Map<String, String> result = new LinkedHashMap<>();
JSONObject inputJSONObj = (JSONObject) new JSONParser().parse(inputJSON);
String id = inputJSONObj.getOrDefault("id", "").toString();
String name = inputJSONObj.getOrDefault("name", "").toString();
String price = ((JSONObject) inputJSONObj.getOrDefault("price", new JSONObject())).getOrDefault("value", "")
.toString();
JSONArray itemsArray = (JSONArray) inputJSONObj.getOrDefault("items", new JSONArray());
int n = itemsArray.size();
String[] itemIDs = new String[n];
for (int i = 0; i < n; i++) {
JSONObject itemObj = (JSONObject) itemsArray.get(i);
String itemId = itemObj.getOrDefault("id", "").toString();
itemIDs[i] = itemId;
}
result.put("id", id);
result.put("name", name);
result.put("price", price);
result.put("items", Arrays.toString(itemIDs));
return result;
}
An approach for you with Gson. This do exactly what you want " represent this as flat map, but I want to represent the array of items as a list"
public class ParseJson1 {
public static void main (String[] args){
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
Gson gson = new Gson();
String json = "{\n" +
" \"id\": \"1\",\n" +
" \"name\": \"Hw\", \n" +
" \"price\": {\n" +
" \"value\": \"10\"\n" +
" },\n" +
" \"items\": [{\n" +
" \"id\": \"1\"\n" +
" }]\n" +
" }\n";
HashMap<String, Object> map = gson.fromJson(json, type);
Object val = null;
for(String key : map.keySet()){
val = map.get(key);
if(val instanceof List){
for(Object s : (List)val){
System.out.println(key + ":" + s);
}
} else
System.out.println(key + ":" + map.get(key));
}
}
}
you have to convert your String in Map collection Map<String, String> which will help you to convert your Map Array to JSON format.
JSONObject jsonObject = new JSONObject();
Map<String, String> mapObject = new HashMap<String, String>();
mapObject.put("id", "1");
mapObject.put("name", "VBage");
mapObject.put("mobile", "654321");
jsonObject.put("myJSON", mapObject);
System.out.println(jsonObject.toString());
First, the JSON does not seems to have a correct format. Do you mean this?
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [{
"id": "1"
}]
}
In addition, since you were attaching the link of (How to deserialize JSON into flat, Map-like structure?), I assume you wants to flatten the JSON in the same manner, in which the result should be
{
id=1,
name=Hw,
price.value=10,
items[0]=1,
}
Also, if you just want the item to return a list of id (i.e. "items": ["1"]), then it is more logical to get a JSON of
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [ "1" ] // instead of "items": [{"id": "1"}]
}
The link that you have attached (How to deserialize JSON into flat, Map-like structure?) provides a general solution without any customization. It shouldn't know that "id" is the value you want to append on items.
Therefore, my first suggestion is to change the JSON to be "items": [ "1" ]
If for any reasons the JSON cannot be changed, then you will need to do some customization, which will be like this:
import org.codehaus.jackson.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.node.ValueNode;
import org.junit.Test;
public class Main {
String json = "{\n" +
" \"id\": \"1\",\n" +
" \"name\": \"Hw\", \n" +
" \"price\": {\n" +
" \"value\": \"10\"\n" +
" },\n" +
" \"items\": [{\n" +
" \"id\": \"1\"\n" +
" }]\n" +
" }\n";
#Test
public void testCreatingKeyValues() {
Map<String, String> map = new HashMap<String, String>();
try {
addKeys("", new ObjectMapper().readTree(json), map);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(map);
}
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.getFields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
// Customization here
if (entry.getKey().equals("items")) {
ArrayNode arrayNode = (ArrayNode) entry.getValue();
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + entry.getKey() + "[" + i + "]", arrayNode.get(i).get("id"), map);
}
} else {
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map);
}
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + "[" + i + "]", arrayNode.get(i), map);
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
}
Try understanding the format that you need, and then study the above code. It should give you the answer.

Can't decode Json array values?

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.

How to store JSONcontaining Nested JSONArray

I'm working on one app in which I have JSON Like..
{
"Group Details":
[
{
"groupMasterId": "25",
"GroupName": "Gangs of Beasts",
"groupIcon": "http://xxx.xxx.xx.x/XYZ/images/evil.png",
"GroupDescription": "Fellowzzzgroup",
"GroupCreatedDate": "2014-04-30 15:41:01",
"GroupMassage": "no such thing is like group msg",
"UserData":
[
{"UserMobile": "1111111111","AdminFlag": "1"},
{"UserMobile": "1234567890","AdminFlag": "0"},
{"UserMobile": "9988776655","AdminFlag": "0"},
{"UserMobile": "234t537535","AdminFlag": "0"},
{"UserMobile": "3489869348","AdminFlag": "0"},
{"UserMobile": "1234567890","AdminFlag": "0"}
]
}
]
}
I want to display Details on simple TextView and UserData in ListView..but the proble in I'm total confused with how to store this data.. I done following code to do it,,but not able to store all UserMobile in single HashMap...
JSONObject jsonObj = new JSONObject(jsonstr);
GroupDetailsArray = jsonObj.getJSONArray(GROUPDETAILS);
HashMap<String, String> groupuser = new HashMap<String, String>();
for (int i = 0; i < GroupDetailsArray.length(); i++) {
JSONObject l = GroupDetailsArray.getJSONObject(i);
// String ID= l.getString(GROUPMASTERID);
String NAME = l.getString(GROUPNAME);
String DESCRIPTION = l.getString(GROUPDESCRIPTION);
String DATE = l.getString(GROUPCREATEDDATE);
String ICON = l.getString(GROUPICON);
JSONArray UsedDataArray = l.getJSONArray(USERDATA);
String ADMIN;
for (int j = 0; j < UsedDataArray.length(); j++) {
JSONObject l1 = UsedDataArray.getJSONObject(j);
if (l1 != null) {
String MOBILENUMBER = l1.getString(USERMOBILE);
if (l1.getString(ADMINFLAG).equals("0")) {
ADMIN = "Member";
} else {
ADMIN = "Admin";
}
// tmp hashmap for single group
groupuser.put(USERMOBILE, MOBILENUMBER);
groupuser.put(ADMINFLAG, ADMIN);
}
}
// tmp hashmap for single group
HashMap<String, String> group = new HashMap<String, String>();
// adding each child node to HashMap key => value
group.put(GROUPNAME, NAME);
group.put(GROUPDESCRIPTION, DESCRIPTION);
group.put(GROUPCREATEDDATE, DATE);
group.put(USERDATA, groupuser.toString());
group.put(GROUPICON, ICON);
// adding group to group list
Utility.groupdetailsarraylist.add(group);
Log.d("groupdetailsarraylist",
Utility.groupdetailsarraylist.toString());
}
please help me to how to store data so that I can use it to store in next Activity...
List list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("UserData");
for(int i=0;i<array.length();i++)
{ list1.add(array.getJSONObject(i).getString("UserMobile"));
}
Iterator itr=list1.iterator();
while(itr.hasNext())
{
str1=itr.next().e+"\n";
}

How can I iterate JSONObject to get individual items

This is my below code from which I need to parse the JSONObject to get individual items. This is the first time I am working with JSON. So not sure how to parse JSONObject to get the individual items from JSONObject.
try {
String url = service + version + method + ipAddress + format;
StringBuilder builder = new StringBuilder();
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
httpget.getRequestLine();
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
// Now iterate jsonObject to get Latitude,Longitude,City,Country etc etc.
}
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
} finally {
bufferedReader.close();
httpclient.getConnectionManager().shutdown();
}
My JSON looks like this:
{
"ipinfo": {
"ip_address": "131.208.128.15",
"ip_type": "Mapped",
"Location": {
"continent": "north america",
"latitude": 30.1,
"longitude": -81.714,
"CountryData": {
"country": "united states",
"country_code": "us"
},
"region": "southeast",
"StateData": {
"state": "florida",
"state_code": "fl"
},
"CityData": {
"city": "fleming island",
"postal_code": "32003",
"time_zone": -5
}
}
}
}
I need to get latitude, longitude, city, state, country, postal_code from the above object. Can anyone provide any suggestion how to do it efficiently?
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"

Categories

Resources