Sorting a JSON object in Android studios (java) - java

I've been searching for a while on how to sort a JSON object like this. It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":
I'm really new to java so you have any information to get started that'll be great!
//update:
So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input
This is the comparator I'm using (got it from the internet)
public class AlphabeticalComparator implements Comparator<String> {
public int compare(String obj1, String obj2) {
if (obj1 == null) {
return -1;
}
if (obj2 == null) {
return 1;
}
if (obj1.equals( obj2 )) {
return 0;
}
return obj1.compareTo(obj2);
}
}
I'm also a little confused on how this sorts the objects since it will only return an integer. The json object im trying to sort is below
This is the JSON Object I get in response when I connect to the zomato API
``
{
"results_found": 10573,
"results_start": 0,
"results_shown": 20,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 16795271
},
"apikey": "fa221c30c201daf8380ac435cedfebe9",
"id": "16795271",
"name": "Craigie On Main", //This is what I want to sort it by
"url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "853 Main St, Cambridge 02139",
"locality": "Central Square",
"city": "Boston",
"city_id": 289,
"latitude": "42.3634820000",
"longitude": "-71.0985660000",
"zipcode": "02139",
"country_id": 216,
"locality_verbose": "Central Square, Boston"
},
"switch_to_order_menu": 0,
"cuisines": "European, French",
"average_cost_for_two": 275,
"price_range": 4,
"currency": "$",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.2",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "342"
},
"photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16795271",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 16798941
},
"apikey": "fa221c30c201daf8380ac435cedfebe9",
"id": "16798941",
"name": "O Ya",
"url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "9 East St, Boston 02111",
"locality": "Leather District",
"city": "Boston",
"city_id": 289,
"latitude": "42.3513170000",
"longitude": "-71.0570370000",
"zipcode": "02111",
"country_id": 216,
"locality_verbose": "Leather District, Boston"
},
"switch_to_order_menu": 0,
"cuisines": "Japanese, Sushi",
"average_cost_for_two": 275,
"price_range": 4,
"currency": "$",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.3",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "192"
},
"photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16798941",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 16798079
},
"apikey": "fa221c30c201daf8380ac435cedfebe9",
"id": "16798079",
"name": "Solea Restaurant and Tapas Bar",
"url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "388 Moody St, Waltham 02453",
"locality": "Waltham",
"city": "Boston",
"city_id": 289,
"latitude": "42.3695490000",
"longitude": "-71.2370130000",
"zipcode": "02453",
"country_id": 216,
"locality_verbose": "Waltham, Boston"
},
"switch_to_order_menu": 0,
"cuisines": "Spanish, Tapas",
"average_cost_for_two": 275,
"price_range": 4,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "4.2",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "303"
},
"photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/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/16798079",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
"restaurant": {
"R": {
"res_id": 16796139
},
"apikey": "fa221c30c201daf8380ac435cedfebe9",
"id": "16796139",
"name": "Harvest",
"url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "44 Brattle St, Cambridge 02138",
"locality": "Harvard Square",
"city": "Boston",
"city_id": 289,
"latitude": "42.3742680000",
"longitude": "-71.1219960000",
"zipcode": "02138",
"country_id": 216,
"locality_verbose": "Harvard Square, Boston"
},
"switch_to_order_menu": 0,
"cuisines": "American, Breakfast",
"average_cost_for_two": 275,
"price_range": 4,
"currency": "$",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "3.9",
"rating_text": "Good",
"rating_color": "9ACD32",
"votes": "190"
},
"photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16796139",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},

Write a Comparator that orders a pair of JSON objects based on their respective name attributes. Then use that to sort your array of JSON objects; e.g. using Arrays.sort(objects, comparator).
Here is a (more general) example:
https://stackoverflow.com/a/45555429/139985
You can modify that code to replace the OffersOrder class with your JSON object type (or a custom class) and then implement the comparator to compare objects and return the appropriate value.

I'm only familiar with using Google's gson library which is a bit old. If there are better json parsers available I'm sure somebody can chime in.
You'd use it like this to extract the information:
String restaurantName;
JsonElement restaurantJSONElement;
JsonPrimitive restaurantJSONPrimitive;
JsonParser parser = new JsonParser();
// myJSONstring is the raw JSON data
JsonElement parentJSONElement = parser.parse(myJSONstring);
JsonObject parentJSONObject = parentJSONElement.getAsJsonObject();
JsonArray restaurantsJSONArray = (JsonArray) parentJSONObject.get("restaurants");
for(int i=0;i<restaurantsJSONArray.size();i++){
//get the element
restaurantJSONElement = ((JsonObject)restaurantsJSONArray.get(i)).get("restaurant");
//get the restaurant name
restaurantJSONPrimitive = ((JsonObject)restaurantJSONElement.getAsJsonObject()).getAsJsonPrimitive("name");
restaurantName = restaurantJSONPrimitive.getAsString();
}
You could extract all the members and do whatever you want with them, put them in custom object arrays and sort them by restaurantName as the comparitor

Related

I want to skip some of the keys from the expected JSON file for comparison with the JSON response

I am new to coding and learning Rest Assured
I have saved a JSON file "expectedResponse.json" with content as:
[
{
"id": 1,
"name": "Resident Evil 4",
"releaseDate": "2005-10-01",
"reviewScore": 85,
"category": "Shooter",
"rating": "Universal"
},
{
"id": 2,
"name": "Gran Turismo 3",
"releaseDate": "2001-03-10",
"reviewScore": 91,
"category": "Driving",
"rating": "Universal"
},
{
"id": 3,
"name": "Tetris",
"releaseDate": "1984-06-25",
"reviewScore": 88,
"category": "Puzzle",
"rating": "Universal"
},
{
"id": 4,
"name": "Super Mario 64",
"releaseDate": "1996-10-20",
"reviewScore": 90,
"category": "Platform",
"rating": "Universal"
},
{
"id": 5,
"name": "The Legend of Zelda: Ocarina of Time",
"releaseDate": "1998-12-10",
"reviewScore": 93,
"category": "Adventure",
"rating": "PG-13"
},
{
"id": 6,
"name": "Doom",
"releaseDate": "1993-02-18",
"reviewScore": 81,
"category": "Shooter",
"rating": "Mature"
},
{
"id": 7,
"name": "Minecraft",
"releaseDate": "2011-12-05",
"reviewScore": 77,
"category": "Puzzle",
"rating": "Universal"
},
{
"id": 8,
"name": "SimCity 2000",
"releaseDate": "1994-09-11",
"reviewScore": 88,
"category": "Strategy",
"rating": "Universal"
},
{
"id": 9,
"name": "Final Fantasy VII",
"releaseDate": "1997-08-20",
"reviewScore": 97,
"category": "RPG",
"rating": "PG-13"
},
{
"id": 10,
"name": "Grand Theft Auto III",
"releaseDate": "2001-04-23",
"reviewScore": 90,
"category": "Driving",
"rating": "Mature"
}
]
However I want to skip some keys like "releaseDate" from comparison with the response as the date field can sometimes have a different format like "2021-03-13T20:22:49.935Z" (just an example) in response.
Currently I am able to assert the response and Expected JSON file with help of following method:=
public static String readFile(String className, String fileName) throws IOException
{
String content = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir")+"\\src\\test\\java\\TestData\\"+className+"\\data\\"+fileName)),StandardCharsets.UTF_8);
return content;
}
public static void responseAssertionWithFile(Response response, String className , String expResponseFile) throws ParseException, IOException
{
JSONParser jsonParser = new JSONParser();
JSONArray respArray = (JSONArray) jsonParser.parse(response.asString());
JSONArray expjsonArray = (JSONArray) jsonParser.parse(readFile(className,expResponseFile));
Assert.assertEquals(respArray.size(), expjsonArray.size());
#SuppressWarnings("unchecked")
Iterator<JSONObject> respIterator = respArray.iterator();
#SuppressWarnings("unchecked")
Iterator<JSONObject> expIterator = expjsonArray.iterator();
while(respIterator.hasNext() && expIterator.hasNext())
{
Assert.assertEquals(respIterator.next(), expIterator.next());
}
}
Override your assertEquals method and exclude the keys you dont want or include only the keys you want, whatever makes more sense in your usecase.
Something like:
public Boolean asserEquals(JSONObject obj1, JSONObject obj2){
String[] keysToExclude = {"releaseDate","whatever"};
for(String key : obj1){
if(!keysToExclude.contains(key) && obj1.get(key)!==obj2.get(key)){
return false;
}
}
return true;
}
This is probably not working Java code. I switched languages so much lately I am gettin them all mixed up. Lets call it pseudocode.
UPDATE:
Real Java code with json-simple
public Boolean assertEquals(JSONObject obj1, JSONObject obj2){
String[] keysToExclude = {"releaseDate","whatever"};
Iterator<String> keyIter = obj1.keySet().iterator();
while(keyIter.hasNext()) {
String key = keyIter.next();
if(!contains(keysToExclude,key) && !obj1.get(key).equals(obj2.get(key))) {
return false;
}
}
retrun true;
}
Oh and you will have to implement the contains function yourself. Here is a pointer: How do I determine whether an array contains a particular value in Java?.

How to write a REST API method for which consume json format for list of objects

I have written a method as following.
#POST
#Path("/add")
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
#Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public boolean createMeasurement(List<MeasurementBean> list ,#HeaderParam(AUTHORIZATION) String authString){
Gson gson = new Gson();
LoginSession loginSession=null;
try{
loginSession = LoginUtility.validateKey(authString);
ResultRO<List<HashMap<String, Object>>> resultRO = loginSession
.execute(new Callable<ResultRO<List<HashMap<String, Object>>>>() {
#Override
public ResultRO<List<HashMap<String, Object>>> call() throws Exception {
String key[] = idKey.split(":");
String type = key[0];
long testId = Long.parseLong("2");
return doGetCreateMeasurement(list ,2);
}
});
return gson.toJson(true);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
I am not able to consume the list of objects from json format.
and my json is in following format
{
"beans": [{
"id": 1133,
"testConditionGroupId": 0,
"testId": 0,
"type": 0,
"completeFlag": 0,
"invalidFlag": 0,
"retentionFlag": 0,
"delBeforeFlag": 0,
"dontReplicateFlag": 0,
"releaseFlag": 0,
"timeBase": 0.0,
"name": "MeaResult_TEST_XYZABCD",
"version": "V.1.0.1",
"description": "M_Test",
"mimeType": "MIME",
"stardDate": "",
"endDate": "",
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}],
"subMatrixList": [{
"id": 0,
"name": "Test_SubMatrixBean1_New",
"version": "V.1.0.0",
"mimeType": "MimeTyep",
"NumberOfvalues": 3,
"noOfRows": 1,
"localColumnList": [{
"id": 0,
"name": "TestName_1_New",
"version": "V.1.0.0",
"mimeType": "MimeTyep",
"sequence_Representation": "explicit",
"independent": 1,
"global_Flag": 15,
"raw_Datatype": 1,
"dataValues": ["1", "2", "3"],
"flags": [15, 15, 15],
"generation_Parameters": [1.0, 2.0, 3.0],
"externalComponents": [],
"attributeList": [],
"meaQuantity": {
"id": 0,
"name": "TestName_1_New",
"unit": "ms",
"quantityName": "MeaQuantity_Quantity",
"description": "MeaQuantity_Test",
"localName": "TestName_1_New",
"size": 10,
"dataType": 1,
"min": 1.0,
"max": 10.0,
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}
}],
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}],
"meaQuantityList": [{
"id": 0,
"name": "TestName_1_New",
"unit": "ms",
"quantityName": "MeaQuantity_Quantity",
"description": "MeaQuantity_Test",
"localName": "TestName_1_New",
"size": 10,
"dataType": 1,
"min": 1.0,
"max": 10.0,
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}]
}]
}
but when I am trying to POST request using postman it gives following error
WARNING: No message body reader has been found for request class MeasurementBeans, ContentType : application/json.
and also method is not executing.
You are accepting a List<MeasurementBean> in the createMeasurement() method and the JSON you have mentioned is an object.
{
"beans": []
//..
}
Just make it as an array by removing the starting {, "beans:" and ending }, i.e you just need to pass the array.

GSON cannot parse Zomato restaurant collection

I am using Java and Akka to design new app at home, but I am facing problems pasing api response from Zomato.
The JSON response can be found below. I've created Class Restaurant with List of objects Restaurant. How should I parse it?
{
"results_found": 131,
"results_start": 0,
"results_shown": 10,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 6103211
},
"apikey": "4972ea7a10293fc07e997364eef03d3d",
"id": "6103211",
"name": "Dishoom",
"url": "https://www.zomato.com/london/dishoom-covent-garden?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "12 Upper St Martin's Lane, Covent Garden, London WC2H 9FB",
"locality": "Upper St Martin's Lane, Covent Garden",
"city": "London",
"city_id": 61,
"latitude": "51.5124170000",
"longitude": "-0.1271640000",
"zipcode": "WC2H 9FB",
"country_id": 215,
"locality_verbose": "Upper St Martin's Lane, Covent Garden, London"
},
"switch_to_order_menu": 0,
"cuisines": "Indian, North Indian, Curry, Cafe",
"average_cost_for_two": 35,
"price_range": 2,
"currency": "\u00a3",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.9",
"rating_text": "Excellent",
"rating_color": "3F7E00",
"votes": "919"
},
"photos_url": "https://www.zomato.com/london/dishoom-covent-garden/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/london/dishoom-covent-garden/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"include_bogo_offers": true,
"deeplink": "zomato://restaurant/6103211",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/london/dishoom-covent-garden/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
If the json is exactly the same of what you've pasted here, it seems that it's not a valid json. Try with this one:
{
"results_found": 131,
"results_start": 0,
"results_shown": 10,
"restaurants": [{
"restaurant": {
"R": {
"res_id": 6103211
},
"apikey": "4972ea7a10293fc07e997364eef03d3d",
"id": "6103211",
"name": "Dishoom",
"url": "https://www.zomato.com/london/dishoom-covent-garden?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "12 Upper St Martin's Lane, Covent Garden, London WC2H 9FB",
"locality": "Upper St Martin's Lane, Covent Garden",
"city": "London",
"city_id": 61,
"latitude": "51.5124170000",
"longitude": "-0.1271640000",
"zipcode": "WC2H 9FB",
"country_id": 215,
"locality_verbose": "Upper St Martin's Lane, Covent Garden, London"
},
"switch_to_order_menu": 0,
"cuisines": "Indian, North Indian, Curry, Cafe",
"average_cost_for_two": 35,
"price_range": 2,
"currency": "\u00a3",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.9",
"rating_text": "Excellent",
"rating_color": "3F7E00",
"votes": "919"
},
"photos_url": "https://www.zomato.com/london/dishoom-covent-garden/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/london/dishoom-covent-garden/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"include_bogo_offers": true,
"deeplink": "zomato://restaurant/6103211",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/london/dishoom-covent-garden/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
}]
}
The first thing is the JSON is invalid. I assume you can manage a valid JSON. After validating the JSON.
Create a Restaurant POJO class first.
The properties for Restaurant class:
R: obj
apikey: string
location: obj
.... like .....
add all the fields that you need.
After that, Use code to parse. but first, fetch out the restaurants array from the JSON.
gson.fromJson(restaurants, Restaurant[].class);

Json full response in Json object or String

hi I am using okhttp for getting my data from the server and I am getting the response by response.body().string() that is printing full data. But when i am converting the response to jsonobject or String(Storing in the variable) and printing data it is not displaying full data of the response.i am unable to display
"id": 1,
"user_id": 1,
"first_name": "hhhh",
"last_name": "Thakur",
while other is working fine
My json data in form
{
"customers": [
{
"id": 1,
"user_id": 1,
"first_name": "hhhh",
"last_name": "Thakur",
"website": "",
"status": 0,
"created": "2017-10-10T07:29:45+00:00",
"customer_info": [
{
"id": 1,
"customer_id": 1,
"created": "2017-10-10T07:29:45+00:00"
}
],
"customer_address": [
{
"id": 1,
"customer_id": 1,
"name": "hhhh Thakur",
"address": "V.PO Chadwal Distt Kathua, Teh Hiranagar Jammu, Jammu and Kashmir in",
"city": "Shimla",
"state": "Himachal Pradesh",
"zip": "171004",
"country": "India",
"fax": "06723",
"type": 1,
"as_ship": 1,
"created": "2017-10-10T07:29:45+00:00"
},
{
"id": 2,
"customer_id": 1,
"name": "Neha Sharma",
"address": "V.PO Chadwal Distt Kathua, Teh Hiranagar Jammu, Jammu and Kashmir in",
"city": "India",
"state": "Jammu and Kashmir",
"zip": "180012",
"country": "India",
"fax": "664984",
"type": 2,
"as_ship": 1,
"created": "2017-10-10T07:29:45+00:00"
}
]
},
{
"id": 2,
"user_id": 1,
"first_name": "arun",
"last_name": "kumar",
"website": "www.isitwa.com",
"status": 0,
"created": "2017-10-11T10:14:38+00:00",
"customer_info": [
{
"id": 2,
"customer_id": 2,
"created": "2017-10-11T10:14:38+00:00"
}
],
"customer_address": [
{
"id": 3,
"customer_id": 2,
"name": "",
"address": "",
"city": "",
"state": "",
"zip": "",
"country": "",
"fax": "",
"type": 1,
"as_ship": 1,
"created": "2017-10-11T10:14:38+00:00"
},
{
"id": 4,
"customer_id": 2,
"name": "",
"address": "",
"city": "",
"state": "",
"zip": "",
"country": "",
"fax": "",
"type": 2,
"as_ship": 1,
"created": "2017-10-11T10:14:38+00:00"
}
]
}
]}
}
That's because your JSON is invalid... Paste your JSON codes here, https://codebeautify.org/jsonviewer , it will allow you to manipulate the formating, and take a better look into it...
I'm not an expert in Java but listing a nested array ( no matter, JSON or plain array ) can be done in two ways:
foreach ( $array as $item) {
foreach ( $item as $key => $data) {
echo $data;
}
}
for ( $i=0; $i < $array.lenght(); $i++ ) {
for ( $j=0; $j < $array.lenght-1; $j++) {
print_r $array[$i][$j];
}
}
Using foreach method is better if you don't know how long, or nested your array is...
Your json data is not well formatted ,try to print below one:
{
"a": [
{
"id": 1,
"user_id": 1,
"first_name": "John",
"last_name": "",
"b": [
{
"id": 1,
"customer_id": 1,
"created": "2017-10-10T07:29:45+00:00"
}
],
"c": [
{
"id": 1,
"customer_id": 1,
"created": "2017-10-10T07:29:45+00:00"
}
]
}],
"b":[{
"id": 1,
"user_id": 1,
"first_name": "John",
"last_name": "",
"b": [
{
"id": 1,
"customer_id": 1,
"created": "2017-10-10T07:29:45+00:00"
}
],
"c": [
{
"id": 1,
"customer_id": 1,
"created": "2017-10-10T07:29:45+00:00"
}
]
}
]}

How to access JSON element which is an array

I have the GSON library in my project, I need the ext_id. I am able to access "images" using the JSON.get("images"), however I am unable to get into the images array. Can someone please help me with this.
{
"images": [{
"attributes": {},
"ext_id": "467152316",
"flag_count": 0,
"height": 2064,
"id": "da2d2307b6b72afcfbd6eab8287fad49fce442d6",
"platform": "Web",
"state_name": "public",
"type_name": "ypid",
"user_id": 7297580,
"user_type": "obile",
"width": 1161,
"verified": 1,
"blob_media_type": "image",
"created_at": "2016-08-19 19:29:13 +0000",
"deleted": 0,
"end_date": "2216-07-02 19:29:13 +0000",
"primary": 0,
"recurring": 0,
"start_date": "2016-08-19 19:29:13 +0000",
"state": 0,
"tags": [],
"type_id": 1,
"updated_at": "2016-08-19 19:29:13 +0000",
"user": "Fanta C.",
"business": {
"name": "Porto's Bakery",
"ypid": "467152316",
"listing_id": "467152316",
"primary_collection": "food",
"heading_code": "8004219",
"mip_url": "/glendale-ca/mip/portos-bakery-467152316",
"phone_number": "(818) 956-5996",
"address": "315 N Brand Blvd",
"heading_text": "Dessert Restaurants",
"city": "Glendale",
"state": "CA",
"zip": "91203",
"is_paid": false,
"tier": 999,
"source": "MDM",
"rating_attributes": [{
"name": "Atmosphere",
"id": 1031
}, {
"name": "Food",
"id": 1023
}, {
"name": "Service",
"id": 1038
}]
}
}],
"count": 1
}
You can try this one.
public void parse(String jsonString) {
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobject = jelement.getAsJsonObject();
JsonArray jarray = jobject.getAsJsonArray("images");
for(int i=0;i<jarray.size();i++){
JsonObject jsonObject = jarray.get(i).getAsJsonObject();
String result = jsonObject.get("ext_id").toString();
System.out.println(result);
result = jsonObject.get("height").toString();
System.out.println(result);
}
}
You can also look here
JsonArray jsonArray = (JsonArray)jObject3.get("images");
JsonObject jObject4 =(JsonObject) jsonArray.get(0);
System.out.println(jObject4.get("ext_id"));
System.out.println(jObject4.get("full_image_path"));

Categories

Resources