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);
Related
Seem to be struggling to calculate the number of squad members who have the role type of 'PLAYER' by performing my restassured logic against my Json response.
Currently I have a simple setup which hits an endpoint and then executes my query, I can see that the endpoint and response is valid however it seems there is a problem when attempting to filter via my query in order to calculate the total sum of squad members who have a role of 'PLAYER'.
My Rest-assured code:
#Test
public void locatePlayerCalculateSum() {
Response response = given()
.spec(footballCompetitions_requestSpecification)
.when().get(EndPoint.TEAMS + EndPoint.SQUAD);
int sum = response.path("squad.collect { it.role == \"PLAYER\" }.sum()");
System.out.println(sum);
}
Exception Message: java.lang.IllegalArgumentException: No signature of method: java.lang.Boolean.plus() is applicable for argument types: (java.lang.Boolean) values: [true]
Possible solutions: is(java.lang.Object), or(java.lang.Boolean), implies(java.lang.Boolean), and(java.lang.Boolean), use([Ljava.lang.Object;), split(groovy.lang.Closure)
Example JSON response:
"id": 66,
"area": {
"id": 2072,
"name": "England"
},
"activeCompetitions": [
{
"id": 2021,
"area": {
"id": 2072,
"name": "England"
},
"name": "Premier League",
"code": "PL",
"plan": "TIER_ONE",
"lastUpdated": "2019-01-03T23:39:45Z"
},
{
"id": 2001,
"area": {
"id": 2077,
"name": "Europe"
},
"name": "UEFA Champions League",
"code": "CL",
"plan": "TIER_ONE",
"lastUpdated": "2018-12-13T18:55:02Z"
}
],
"name": "Manchester United FC",
"shortName": "Man United",
"tla": "MNU",
"crestUrl": "http://upload.wikimedia.org/wikipedia/de/d/da/Manchester_United_FC.svg",
"address": "Sir Matt Busby Way Manchester M16 0RA",
"phone": "+44 (0161) 8688000",
"website": "http://www.manutd.com",
"email": "enquiries#manutd.co.uk",
"founded": 1878,
"clubColors": "Red / White",
"venue": "Old Trafford",
"squad": [
{
"id": 3188,
"name": "David De Gea",
"position": "Goalkeeper",
"dateOfBirth": "1990-11-07T00:00:00Z",
"countryOfBirth": "Spain",
"nationality": "Spain",
"shirtNumber": 1,
"role": "PLAYER"
},
{
"id": 3202,
"name": "Sergio Romero",
"position": "Goalkeeper",
"dateOfBirth": "1987-02-22T00:00:00Z",
"countryOfBirth": "Argentina",
"nationality": "Argentina",
"shirtNumber": null,
"role": "PLAYER"
},
{
"id": 7942,
"name": "Lee Grant",
"position": "Goalkeeper",
"dateOfBirth": "1983-01-27T00:00:00Z",
"countryOfBirth": "England",
"nationality": "England",
"shirtNumber": 13,
"role": "PLAYER"
},
{
"id": 3206,
"name": "Marcos Rojo",
"position": "Defender",
"dateOfBirth": "1990-03-20T00:00:00Z",
"countryOfBirth": "Argentina",
"nationality": "Argentina",
"shirtNumber": 16,
"role": "PLAYER"
},```
This should work:
#Test
public void locatePlayerCalculateSum() {
Response response = given()
.spec(footballCompetitions_requestSpecification)
.when().get(EndPoint.TEAMS + EndPoint.SQUAD);
int sum = response.path("squad.count { it.role == 'PLAYER' }");
System.out.println(sum);
}
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.
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
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"
}
]
}
]}
I want to pull out the user block. The JSON result will always change, sometimes 4 users will be returned, sometimes 10 etc.
{
"results": [
{
"user": {
"avatar_url_thumb": "http://avatars.stocktwits.com/production/9998/thumb-1270014645.png?1270014645",
"avatar_url_medium": "http://avatars.stocktwits.com/production/9998/medium-1270014645.png?1270014645",
"created_at": "2010-03-15T05:44:51Z",
"following_count": 14,
"updated_at": "2010-08-30T18:22:15Z",
"id": 9998,
"updates_count": 31,
"avatar_url_large": "http://avatars.stocktwits.com/production/9998/large-1270014645.png?1270014645",
"investor_relations": false,
"last_name": "Reporter",
"followers_count": 25,
"recommended": false,
"bio": "Apple News & AAPL Stock Analysis, visit Apple Digest blog link above",
"login": "AppleReporter",
"first_name": "Apple"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-04-14T01:02:05Z",
"following_count": 0,
"updated_at": "2010-08-30T18:29:56Z",
"id": 12924,
"updates_count": 1,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Shareholder",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "Imurphit",
"first_name": "Apple"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-04-17T20:52:09Z",
"following_count": 0,
"updated_at": "2010-08-30T18:31:23Z",
"id": 13234,
"updates_count": 0,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Apple",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "apple11",
"first_name": "John"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-07-12T19:04:51Z",
"following_count": 0,
"updated_at": "2010-08-30T20:12:15Z",
"id": 18691,
"updates_count": 0,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Smith",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "apple",
"first_name": "Jacob"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-07-13T17:06:27Z",
"following_count": 0,
"updated_at": "2010-08-30T20:12:30Z",
"id": 18808,
"updates_count": 3,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "apple",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "applejames",
"first_name": "James"
}
}
],
"page": 1,
"symbol": false,
"per_page": 20,
"response": {
"status": 200
},
"total_pages": 1,
"total_entries": 6
}
Use the JSONObject
// Get some JSON from wherever
String json = getJSONFromServer();
// Parse the JSON response into an object
JSONObject object = new JSONObject(json);
// Get the results array
JSONArray users = object.getJSONArray("results");
for(int i = 0; i < users.length(); i++) {
// Each element in the results array is a JSONObject with a single
// property "user" which is a JSONObject that contains the user data
JSONObject user = users.getJSONObject(i).getJSONObject("user");
// Do something with the user
String firstName = user.getString("first_name");
}