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"));
Related
I would like to ask if it is possible to group the object by another object inside its common array.
Here's the JSON response, I need to group the list of item by program id.
I'm trying to put it on the HashMap but it didn't work well.
{
"id": "",
"ordered_by": 64,
"order_details": [
{
"resource": "Product",
"required_prescription": false,
"item": {
"id": 6,
"name": "Synergistic Copper Gloves",
"code": "51537661-C",
"enabled": true,
"generic_name": "Mediocre Steel Wallet",
"price_cents": 200000
},
"program": {
"id": 12,
"name": "Synergistic Wooden Shoes",
"provider": "Synergistic Rubber Coat",
"discount_type": "fixed"
}
},
{
"resource": "Product",
"required_prescription": true,
"item": {
"id": 7,
"name": "Rustic Leather Table",
"code": "74283131-P",
"enabled": true,
"generic_name": "Incredible Bronze Clock",
"price_cents": 8994
},
"program": {
"id": 12,
"name": "Synergistic Wooden Shoes",
"provider": "Synergistic Rubber Coat",
"discount_type": "fixed"
}
},
{
"resource": "Product",
"required_prescription": false,
"item": {
"id": 116,
"name": "Ergonomic Marble Hat",
"code": "98845056-A",
"enabled": true,
"generic_name": "Incredible Granite Lamp",
"price_cents": 8267
},
"program": {
"id": 10,
"name": "Durable Rubber Bag",
"provider": "Aerodynamic Steel Chair",
"discount_type": "fixed"
}
}
]}
This should be the expected object after grouping. The item was grouped by program id 12 & 10.
[
{
"id": 12,
"name": "Synergistic Wooden Shoes",
"provider": "Synergistic Rubber Coat",
"discount_type": "fixed",
"item": [
{
"id": 6,
"name": "Synergistic Copper Gloves",
"code": "51537661-C",
"enabled": true,
"generic_name": "Mediocre Steel Wallet",
"price_cents": 200000
},
{
"id": 7,
"name": "Rustic Leather Table",
"code": "74283131-P",
"enabled": true,
"generic_name": "Incredible Bronze Clock",
"price_cents": 8994
}
]
},
{
"id": 10,
"name": "Durable Rubber Bag",
"provider": "Aerodynamic Steel Chair",
"discount_type": "fixed",
"item": [
{
"id": 116,
"name": "Ergonomic Marble Hat",
"code": "98845056-A",
"enabled": true,
"generic_name": "Incredible Granite Lamp",
"price_cents": 8267
}
]
}
]
All comments would be highly appreciated. Thanks in advance!
I have taken your source json and tried to convert it as per your specification and this is the solution which is working, pass your source JSON as string and you will get the desired output
private String parseJson(String source) {
JSONArray result = new JSONArray();
List<Integer> ids = new ArrayList<>();
HashMap<Integer,JSONObject> programs = new HashMap<>();
try {
JSONObject jSource = new JSONObject(source);
JSONArray orderDetails = jSource.getJSONArray("order_details");
if (orderDetails.length() > 0) {
for (int i = 0; i < orderDetails.length(); i++) {
JSONObject jsonObject = orderDetails.getJSONObject(i);
JSONObject item = jsonObject.getJSONObject("item");
JSONObject program = jsonObject.getJSONObject("program");
int programId = jsonObject.getJSONObject("program").getInt("id");
if (!ids.contains(programId)) {
ids.add(programId);
program.put("item",new JSONArray().put(item));
programs.put(programId,program);
}else{
program.put("item",programs.get(programId).getJSONArray("item").put(item));
}
}
for(int k :programs.keySet()){
result.put(programs.get(k));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
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.
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 can't understand, why I have this error:
04-24 22:11:51.263: W/System.err(27504): org.json.JSONException: Value
<!--HERE JSON VALUE--> at data of type org.json.JSONObject cannot be
converted to JSONArray
This is my code:
JSONObject getProgile = null;
try {
//get json
getProgile = new JSONObject(CustomHttpClient.executeHttpGet(profileGetURL).toString());
//convert array
JSONArray array = getProgile.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
//get TAG_CUSTOMER
JSONObject customer = c.getJSONObject("Customer");
pName = customer.getString("name");
pLname = customer.getString("name");
}
UPD:
My json
{
"status": "success",
"data": {
"Customer": {
"id": "33",
"company_id": "1",
"name": "SDfsdf",
"birthdate": "14.02.1989",
"email": "dsfsdf#sf.ff",
"photo": "/files/clients_photos/33/(null)",
"bonuses": "50",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46",
"ref_id": null,
"ref_code": "6363696029",
"banned": null,
"ban_reason": null,
"ban_ending": null
},
"CustomerVisit": [],
"CustomerBonus": [
{
"id": "29",
"customer_id": "33",
"user_id": "4",
"product_id": null,
"operation": "plus",
"amount": "50",
"subject": "Загрузка фото при регистрации.",
"remain": null,
"modified": "2015-02-14 12:22:46",
"date": "14.02.2015",
"created": "14.02.2015 12:22"
}
],
"CustomerCar": [
{
"id": "41",
"customer_id": "33",
"car_brand_id": "9",
"car_model_id": "11530",
"year": "2020",
"vin": "sdfsdfsdf",
"photo": "",
"number": "dsfsdf",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46",
"car_brand_name": "BMW",
"car_model_name": "323"
}
],
"CustomerPhone": [
{
"id": "41",
"customer_id": "33",
"phone": "+380990010222",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46"
}
],
"Insurance": [],
"Event": [],
"Review": [],
"Reservation": []
}
}
JSON shows data is JSONObject rather than JSONArray, so call getProfile.getJSONObject ("data")
The problem is that you are trying to convert and JSON Object with JSON array therefore an error will occur.
If you just want to get the name then you can do this:
getProgile = new JSONObject(CustomHttpClient.executeHttpGet(profileGetURL).toString());
JSONObject obj1 = getProgile.getJSONObject("data");
JSONObject obj2 = array.getJSONObject("Customer");
String name = obj2.getString("name");
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");
}