JSON decode in android - java

How can I retrieve value from this JSON in android?
I want to create an ArrayList. I've tried JSONObject to access the value. But It need to create object for every city. I want to access all city using a loop inside it like as follows.
{
"City A": {
"Position": {
"Longitude": 9.96233,
"Latitude": 49.80404
}
},
"City B": {
"Position": {
"Longitude": 6.11499,
"Latitude": 50.76891
}
},
"City C": {
"Position": {
"Longitude": 6.80592,
"Latitude": 51.53548
}
},
"City D": {
"Position": {
"Longitude": 9.50523,
"Latitude": 51.31991
}
},
"City E": {
"Position": {
"Longitude": 9.66089,
"Latitude": 48.70158
}
},
"City F": {
"Position": {
"Longitude": 9.93368,
"Latitude": 53.55608
}
},
"City G": {
"Position": {
"Longitude": 11.56122,
"Latitude": 48.14496
}
},
"City H": {
"Position": {
"Longitude": 13.34253,
"Latitude": 52.5319
}
},
"City I": {
"Position": {
"Longitude": 6.11327,
"Latitude": 50.77715
}
},
"City J": {
"Position": {
"Longitude": 13.36671,
"Latitude": 52.54344
}
}
}
How can I manage this when I want the same?

You can do this:
City.java (model class)
public class City implements Comparable {
private String name; // The name of the city
private double latitude; // its latitude
private double longitude; // its longitude
public City(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
#Override
public String toString() {
return name + ": " + latitude + " - " + longitude;
}
#Override
public int compareTo(Object c) {
City city = (City) c;
return name.compareTo(city.name);
}
}
App.java:
public class App {
public static void main(String[] args) {
// Your JSON string
String jsonString = "{\"City A\":{\"Position\":{\"Longitude\":9.96233,\"Latitude\":49.80404}},\"City B\":{\"Position\":{\"Longitude\":6.11499,\"Latitude\":50.76891}},\"City C\":{\"Position\":{\"Longitude\":6.80592,\"Latitude\":51.53548}},\"City D\":{\"Position\":{\"Longitude\":9.50523,\"Latitude\":51.31991}},\"City E\":{\"Position\":{\"Longitude\":9.66089,\"Latitude\":48.70158}},\"City F\":{\"Position\":{\"Longitude\":9.93368,\"Latitude\":53.55608}},\"City G\":{\"Position\":{\"Longitude\":11.56122,\"Latitude\":48.14496}},\"City H\":{\"Position\":{\"Longitude\":13.34253,\"Latitude\":52.5319}},\"City I\":{\"Position\":{\"Longitude\":6.11327,\"Latitude\":50.77715}},\"City J\":{\"Position\":{\"Longitude\":13.36671,\"Latitude\":52.54344}}}";
JSONObject jsonObj = new JSONObject(jsonString);
List<City> cities = new ArrayList<>(); // The arraylist that will hold the cities
// A JSON array with the the names of all the cities
JSONArray cityNames = jsonObj.names();
for(int i = 0; i < jsonObj.length(); i++) {
String cityName = cityNames.getString(i);
JSONObject jsonCity = jsonObj.getJSONObject(cityName);
JSONObject jsonPosition = jsonCity.getJSONObject("Position");
cities.add(new City(cityName, jsonPosition.getDouble("Latitude"), jsonPosition.getDouble("Longitude")));
}
Collections.sort(cities); // Sort the cities' arraylist by city name
cities.forEach(System.out::println); // Print the cities
}
}
Output:
City A: 49.80404 - 9.96233
City B: 50.76891 - 6.11499
City C: 51.53548 - 6.80592
City D: 51.31991 - 9.50523
City E: 48.70158 - 9.66089
City F: 53.55608 - 9.93368
City G: 48.14496 - 11.56122
City H: 52.5319 - 13.34253
City I: 50.77715 - 6.11327
City J: 52.54344 - 13.36671

You can use Google gson to convert string to Java object.

TO get Data with for loop you should have JSONArray.
This is response you should use.
Then using this code you can apply for loop and List or ArrayList to save data.
[{
"city_name": "City A",
"Position": {
"Longitude": 9.96233,
"Latitude": 49.80404
}
}, {
"city_name": "City B",
"Position": {
"Longitude": 6.11499,
"Latitude": 50.76891
}
}, {
"city_name": "City C",
"Position": {
"Longitude": 6.80592,
"Latitude": 51.53548
}
}, {
"city_name": "City D",
"Position": {
"Longitude": 9.50523,
"Latitude": 51.31991
}
}, {
"city_name": "City E",
"Position": {
"Longitude": 9.66089,
"Latitude": 48.70158
}
}, {
"city_name": "City F",
"Position": {
"Longitude": 9.93368,
"Latitude": 53.55608
}
}, {
"city_name": "City G",
"Position": {
"Longitude": 11.56122,
"Latitude": 48.14496
}
}, {
"city_name": "City H",
"Position": {
"Longitude": 13.34253,
"Latitude": 52.5319
}
}, {
"city_name": "City I",
"Position": {
"Longitude": 6.11327,
"Latitude": 50.77715
}
}, {
"city_name": "City J",
"Position": {
"Longitude": 13.36671,
"Latitude": 52.54344
}
}]
then Java code as:
JSONArray json_array= new JSONArray(responseString);
for(int i= 0; i<json_array.length(); i++){
JSONObject json_object = json_array.get(i);
String cityname=json_object.getString("city_name");
JSONObject json_object_position = json_object.getJSONObject("Position");
long longitude=json_object_position.getString("Longitude");
long latitude=json_object_position.getString("Latitude");
// Save the data in List you want.
}

You can use names() method of JSONObject.
Try this :
JSONObject jsonObject = new JSONObject(yourjsonString);
JSONArray jarray = jsonObject.names();
for(int i= 0; i<jarray.length(); i++){
String name = jarray.getString(i);
}

Related

JSONObject - how can I get a value from the response?

I have a response which contains values which I need.
private void getDataFromDistanceMatrixToSaveAndAddToList(
GRATestDataImport place, String response) {
JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0);
}
'response' in params includes:
{
"destination": [
"54.375,18.59"
],
"origin": [
"54.001,21.721"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "304.4 km",
"value": 304403
},
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"status": "OK"
}
]
}
],
"status": "OK"
}
value: 'responseAsJson' in my method is:
{
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"distance": {
"text": "304.4 km",
"value": 304403
},
"status": "OK"
}
How can I get value from the duration and the distance ?
you'll just have to navigate along
int duration = responseAsJson.getJSONObject("duration").getInt("value");
int distance = responseAsJson.getJSONObject("distance").getInt("value");
public class YourResponse
{
public string duration { get; set; }
public string distance { get; set; }
}
YourResponse response = JsonSerializer.Deserialize<YourResponse>(result);

How can I set label names manually on a loop springboot?

I have a JSON array below, I want to be able to set label names that make sense instead of the entity names. Am generating tables dynamically using this data, I want the rows to have names that make more sense to the end user by assigning custom Label names. the recordtype generates new tab names
This is my JSON
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "hCounty",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "hPUM",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is how I want the labels to appear
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "County Name",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "House Code",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is my logic
public ArrayList<Summary> getHouseHoldRecordsByCase(String country, String projectId, String case) {
ArrayList<Summary> documents= new ArrayList<>();
Summary summary = new Summary();
ArrayList<ItemDetails> details = new ArrayList<>();
COVER cover = dataStoreService.getHouseHoldRecordsByCase(country, projectId, caseNumber);
summary.case = caseNumber;
summary.recordType = "Identification";
summary.country = country;
summary.projectId = projectId;
Field[] fields = hsecover.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(hsecover, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
summary = new Summary();
ELIGILITY elig = dataStoreService.getEliByCase(country, projectId, case);
summary.recordType = "Eligibility";
summary.case = case;
summary.country = country;
summary.projectId = projectId;
details = new ArrayList<>();
fields = elig.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(elig, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
}
return documents;
}
public COVER getHouseHoldRecordsByCase(String country, String projectId, String case) {
COVER usa = cover_repository.findByCase(case);
return usa;
}
public ELIGILITY getEliByCase(String country, String projectId, String case) {
ELIGILITY usa = eligility_repository.findByCaseNumber(case);
return usa;
}
My ItemDetails model class
public class ItemDetails {
public String ItemValue;
public String Label;
public String ItemValueLabel;
public String Name;
public ItemDetails(String itemValue, String label, String itemValueLabel, String name) {
ItemValue = itemValue;
Label = label;
ItemValueLabel = itemValueLabel;
Name = name;
}
}
My Summary class
public class Summary {
public String country;
public String projectId;
public String case;
public String recordType;
public ArrayList<ItemDetails> itemDetails;
}
The data comes from a database.
How can I set the label names with names that make sense instead of coming as entity names?
You Can use #JsonProperty("different names") on each fields
Or you can use #JsonSetter("different name") on setter method level.

How can i deserialize this JSON

This is my JSON data i want to parse but am still new in deserialization, i want to get the following Attributes from this JSON data :
1.AirportCode.
2.Latutude.
3.Longitude.
This is the JSON containing two lists of the Airports.
{
"AirportResource": {
"Airports": {
"Airport": [{
"AirportCode": "AAL",
"Position": {
"Coordinate": {
"Latitude": 57.09305556,
"Longitude": 9.85
}
},
"CityCode": "AAL",
"CountryCode": "DK",
"LocationType": "Airport",
"Names": {
"Name": [{
"#LanguageCode": "xx",
"$": "Aalborg"
}, {
"#LanguageCode": "de",
"$": "Aalborg"
}, {
"#LanguageCode": "ru",
"$": "Ольборг"
}, {
"#LanguageCode": "pt",
"$": "Aalborg"
}, {
"#LanguageCode": "jp",
"$": "オールボア"
}, {
"#LanguageCode": "kr",
"$": "올보르그"
}, {
"#LanguageCode": "en",
"$": "Aalborg"
}, {
"#LanguageCode": "it",
"$": "Aalborg"
}, {
"#LanguageCode": "fr",
"$": "Aalborg"
}, {
"#LanguageCode": "es",
"$": "Aalborg"
}, {
"#LanguageCode": "ka",
"$": "奧爾堡"
}, {
"#LanguageCode": "pl",
"$": "Aalbork"
}, {
"#LanguageCode": "mi",
"$": "奥尔堡"
}]
},
"UtcOffset": 2,
"TimeZoneId": "Europe\/Copenhagen"
}, {
"AirportCode": "AAR",
"Position": {
"Coordinate": {
"Latitude": 56.30388889,
"Longitude": 10.62
}
},
"CityCode": "AAR",
"CountryCode": "DK",
"LocationType": "Airport",
"Names": {
"Name": [{
"#LanguageCode": "xx",
"$": "Aarhus"
}, {
"#LanguageCode": "en",
"$": "Aarhus"
}, {
"#LanguageCode": "de",
"$": "Aarhus"
}, {
"#LanguageCode": "it",
"$": "Aarhus"
}, {
"#LanguageCode": "fr",
"$": "Aarhus"
}, {
"#LanguageCode": "es",
"$": "Aarhus"
}]
},
"UtcOffset": 2,
"TimeZoneId": "Europe\/Copenhagen"
}]
},
"Meta": {
"#Version": "1.0.0",
"Link": [{
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=0",
"#Rel": "self"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=2",
"#Rel": "next"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=1260",
"#Rel": "last"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/cities\/{cityCode}",
"#Rel": "related"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/countries\/{countryCode}",
"#Rel": "related"
}],
"TotalCount": 1261
}
}
}
Then my Java code:
EDITTED:
private void parseJson(String result)
{
try {
if (result!=null) {
JSONObject obj = new JSONObject(result).getJSONObject("AirportResource").getJSONObject("Airports");
JSONArray arr = obj.getJSONArray("Airport");
for (int i = 0; i < arr.length(); i++)
{
String AirportCode = arr.getJSONObject(i).getString("AAL");
String Latitude = arr.getJSONObject(i).getJSONObject("Position").getJSONObject("Coordinate").getString("Latitude");
String Longitude = arr.getJSONObject(i).getJSONObject("Position").getJSONObject("Coordinate").getString("Longitude");
System.out.println("Airport : " + AirportCode + " Latitude: " + Latitude+
" Longitude : " + Longitude );
}
}
else{
Toast.makeText(MainActivity.this,Config.POOR_NETWORK_CONNECTION, Toast.LENGTH_LONG).show();
}
}
catch (JSONException r){
System.out.println("ERROR PROB : "+ r);
}
}
The exception am getting is :
org.json.JSONException: No value for AirportResource
How can i parse this JSON kind of Data?
This will HOPEFULLY get you started.
private static void parseJson(JSONObject object) throws JSONException {
if (object!=null) {
JSONObject airportResource = object.getJSONObject("AirportResource");
JSONObject airports = airportResource.getJSONObject("Airports");
JSONArray airportArray = airports.getJSONArray("Airport");
for (int i = 0 ; i < airportArray.length(); i++) {
JSONObject airport = (JSONObject) airportArray.get(i);
//System.out.println(airport);
System.out.println("CityCode: " + airport.getString("CityCode"));
}
}
else{
//null
}
}
The output will be:
CityCode: AAL
CityCode: AAR
You didnt take the object of Airports. Inside Airports object is the Airport array and you are directly accessing it. Hence throwing error.
JSONObject obj2 = obj.getJSONObject("Airports");
Now get Json Array from obj
JsonArray jsonarray= obj2.getJsonArray("Airport");
Use the for loop on jsonarray's length now.
I recommend using this tool to view and formate your JSON properly.
this is the result
from here you could easily resolve your problem
JSONObject AirportResource= obj.getJSONObject("AirportResource");
JsonArray AirPorts= AirportResource.getJSONObject("Airports");
JsonArray jsonarray= AirPorts.getJsonArray("Airport");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj= AirportResource.get(i); do sth with it
obj.getString("key"); //do sth with it
}

Unable to extract out name in 4 level deep nested JSON array

I am trying to create android app that shows details about the restaurants. I have parseJSON function which takes string json as an argument. What I am trying to do for now is to show name of individual restaurants in the json below. I am able to extract individual restaurant(3 levels deep) and print them out through log.d console but I am not able to extract out the individual restaurant's name. Here is the code
public void parseJSON(String jsonQuery){
//Parsing JSON
try {
JSONObject jsonObject = new JSONObject(jsonQuery);
if (jsonObject != null){
JSONArray restaurants = jsonObject.getJSONArray("restaurants");
for (int i = 0; i < restaurants.length(); i++){
JSONObject restaurant = restaurants.getJSONObject(i);
if (restaurant != null){
String tempName = restaurant.getString("name");
Log.d(TAG, "Restaurant name: " + tempName);
}
}
}
} catch (JSONException e) {
Log.d(TAG, "Exception catched: " + e);
e.printStackTrace();
}
}
Here is my json file.
{
"results_found": 1281966,
"results_start": 0,
"results_shown": 2,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 16607974
},
"apikey": "123456789",
"id": "16607974",
"name": "Bassine Specialty Cheese",
"url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "2125 Bass Hwy",
"locality": "Bass",
"city": "Bass",
"city_id": 1341,
"latitude": "-38.4833750000",
"longitude": "145.4670320000",
"zipcode": "3995",
"country_id": 14,
"locality_verbose": "Bass, Bass"
},
"switch_to_order_menu": 0,
"cuisines": "Ice Cream",
"average_cost_for_two": 7,
"price_range": 1,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "2.9",
"rating_text": "Average",
"rating_color": "FFBA00",
"votes": "5"
},
"photos_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16607974",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 17649424
},
"apikey": "3d93604b4a84d85f374f39ea3b644132",
"id": "17649424",
"name": "Schobels' Restaurant",
"url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "2020 Milam St 78934",
"locality": "Columbus",
"city": "Columbus",
"city_id": 9241,
"latitude": "29.6965000000",
"longitude": "-96.5405000000",
"zipcode": "78934",
"country_id": 216,
"locality_verbose": "Columbus, Columbus"
},
"switch_to_order_menu": 0,
"cuisines": "German, Southern",
"average_cost_for_two": 25,
"price_range": 2,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "4.0",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "164"
},
"photos_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/17649424",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
}
]
}
Error which I am getting:
org.json.JSONException: No value for name
Your jsonQuery contain JsonObject inside JsonObject named restaurant so you need to get JsonObject from JSONObject restaurant = restaurants.getJSONObject(i);
Like JSONObject restaurantsJSONObject =restaurant.getJSONObject("restaurant");
Try below example to get name from object
try {
JSONObject jsonObject = new JSONObject(jsonQuery);
if (jsonObject != null){
JSONArray restaurants = jsonObject.getJSONArray("restaurants");
for (int i = 0; i < restaurants.length(); i++){
JSONObject restaurant = restaurants.getJSONObject(i);
JSONObject restaurantsJSONObject =restaurant.getJSONObject("restaurant");
if(restaurantsJSONObject.has("name")) {
String tempName = restaurantsJSONObject.getString("name");
Log.d(TAG, "Restaurant name: " + tempName);
}
}
}
} catch (JSONException e) {
Log.d(TAG, "Exception catched: " + e);
e.printStackTrace();
}

How to parse the following JSON

Here I am getting following JSON from local asset folder. All the JSON object is different in their name. Line 1, 3, 5, 7 .... upto 1000. Herewith I have attached the json for your reference.
{
"status": {
"rcode": 200,
"message": "OK"
},
"data": {
"0": {
"OutletName": "Test 1 ",
"Latitude": "16.123234",
"Longitude": "79.546745"
},
"1": {
"OutletName": "Test 2",
"Latitude": "16.343234",
"Longitude": "79.786745"
},
"2": {
"OutletName": "Test 3",
"Latitude": "19.1294",
"Longitude": "72.836122"
},
"3": {
"OutletName": "Test 4",
"Latitude": "19.136383",
"Longitude": "72.827997"
},
"6": {
"OutletName": "Test 5",
"Latitude": "19.136715",
"Longitude": "72.829248"
},
"7": {
"OutletName": "Test 6",
"Latitude": "19.128483",
"Longitude": "72.821199"
},
"8": {
"OutletName": "Test 7",
"Latitude": "19.128528",
"Longitude": "72.819388"
},
"10": {
"OutletName": "Test 8",
"Latitude": "19.140333",
"Longitude": "72.831095"
},
"11": {
"OutletName": "Test 9",
"Latitude": "19.14027",
"Longitude": "72.826285"
}
}
}
Here the Object name is different for all. So I try like this
private void parseJson() {
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONObject jObj = obj.getJSONObject("data");
System.out.println("jObj.length()==> " + jObj.length());
for (int i = 0; i < jObj.length(); i++) {
if (jObj.has(String.valueOf(i)) && !jObj.isNull(String.valueOf(i))) {
JSONObject jObj1 = jObj.getJSONObject(String.valueOf(i));
System.out.println("Index==> "+i);
System.out.println("OutletName==> "+jObj1.getString("OutletName"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But here I not getting all the data. Please help me to parse this kind of JSON.
Thanks in advance.
You need to use the keys method like this:
private void parseJson() {
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONObject jObj = obj.getJSONObject("data");
Iterator iter = jObj.keys()
while(iter.hasNext()) {
String key = (String) iter.next();
JSONObject jObj1 = jObj.getJSONObject(key);
System.out.println("Index==> "+ key);
System.out.println("OutletName==> "+jObj1.getString("OutletName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Edit:
fixed some type conversion
The value of "data" in your JSON is not an array, hence you cannot iterate over it directly. You will need to first convert it into a HashMap and then iterate over the keyset. You can use Jackson library to convert JSONObject to HashMap. You can also refer to this answer for conversion to map.
first of all you will have to do changes in your json response
{
"status": {
"rcode": 200,
"message": "OK"
},
"data": { //this has to be array in your json
"0": { // and these are object inside the arrays
"OutletName": "Test 1 ",
"Latitude": "16.123234",
"Longitude": "79.546745"
},
"1": { // and these are object inside the arrays
"OutletName": "Test 2",
"Latitude": "16.343234",
"Longitude": "79.786745"
},
"2": {
"OutletName": "Test 3",
"Latitude": "19.1294",
"Longitude": "72.836122"
},
"3": {
"OutletName": "Test 4",
"Latitude": "19.136383",
"Longitude": "72.827997"
},
"6": {
"OutletName": "Test 5",
"Latitude": "19.136715",
"Longitude": "72.829248"
},
"7": {
"OutletName": "Test 6",
"Latitude": "19.128483",
"Longitude": "72.821199"
},
"8": {
"OutletName": "Test 7",
"Latitude": "19.128528",
"Longitude": "72.819388"
},
"10": {
"OutletName": "Test 8",
"Latitude": "19.140333",
"Longitude": "72.831095"
},
"11": {
"OutletName": "Test 9",
"Latitude": "19.14027",
"Longitude": "72.826285"
}
}
}
and dont over json object for its size to access its object it has to be JSONArray
get the array data in JSONArray like this
JSONArray dataArray = response_obj.getJSONArray("data");
and then iterate like this
for (int i = 0; i < dataArray.length(); i++)
{
//write your code here to access all the object as for loop executes on by one
}

Categories

Resources