how to parse json array using retrofit android [duplicate] - java

This question already has answers here:
Parse JSON array response using Retrofit & Gson
(4 answers)
Closed 4 years ago.
{
"name": "",
"link": "",
"menuId": "",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Dashboard",
"link": "/welcome",
"menuId": "das",
"icon": "fa fa-tachometer fa-2x",
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Master",
"link": "",
"menuId": "emp",
"icon": "fa fa-user-plus fa-2x",
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Roles",
"link": "/myRoles",
"menuId": "emp-usr-rol",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Role",
"link": null,
"menuId": "emp-usr-rol-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Role",
"link": null,
"menuId": "emp-usr-rol-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Role",
"link": null,
"menuId": "emp-usr-rol-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Role",
"link": null,
"menuId": "emp-usr-rol-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "User",
"link": "/users",
"menuId": "emp-usr",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create User",
"link": null,
"menuId": "emp-usr-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete User",
"link": null,
"menuId": "emp-usr-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit User",
"link": null,
"menuId": "emp-usr-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List User",
"link": null,
"menuId": "emp-usr-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Departments",
"link": "/department",
"menuId": "emp-mst-dpt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Department",
"link": null,
"menuId": "emp-mst-dpt-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Department",
"link": null,
"menuId": "emp-mst-dpt-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Department",
"link": null,
"menuId": "emp-mst-dpt-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Department",
"link": null,
"menuId": "emp-mst-dpt-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Salary Template",
"link": "",
"menuId": "emp-usr-rol",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Salary Template",
"link": null,
"menuId": "emp-usr-rol-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Salary Template",
"link": null,
"menuId": "emp-usr-rol-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Salary Template",
"link": null,
"menuId": "emp-usr-rol-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Salary Template",
"link": null,
"menuId": "emp-usr-rol-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Job Schedular",
"link": "",
"menuId": "emp-usr-rol",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Job Schedular",
"link": null,
"menuId": "emp-usr-rol-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Job Schedular",
"link": null,
"menuId": "emp-usr-rol-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Job Schedular",
"link": null,
"menuId": "emp-usr-rol-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Job Schedular",
"link": null,
"menuId": "emp-usr-rol-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Shift Management",
"link": "",
"menuId": "emp-usr-rol",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Shift Management",
"link": null,
"menuId": "emp-usr-rol-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Shift Management",
"link": null,
"menuId": "emp-usr-rol-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Shift Management",
"link": null,
"menuId": "emp-usr-rol-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Shift Management",
"link": null,
"menuId": "emp-usr-rol-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Leave Management",
"link": "/holidays",
"menuId": "hrm",
"icon": "fa fa-briefcase fa-2x",
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Holidays",
"link": "/holidays",
"menuId": "emp-mst-hdy",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Holiday",
"link": null,
"menuId": "emp-mst-hdy-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Holiday",
"link": null,
"menuId": "emp-mst-hdy-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Holiday",
"link": null,
"menuId": "emp-mst-hdy-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Holiday",
"link": null,
"menuId": "emp-mst-hdy-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Leave Template",
"link": "",
"menuId": "emp-usr-rol",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Create Leave Template",
"link": null,
"menuId": "emp-usr-rol-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Leave Template",
"link": null,
"menuId": "emp-usr-rol-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Leave Template",
"link": null,
"menuId": "emp-usr-rol-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Leave Template",
"link": null,
"menuId": "emp-usr-rol-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
}
]
}
]
},
{
"name": "Employee Management",
"link": "",
"menuId": "emng",
"icon": "fa fa-user fa-2x",
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Employee",
"link": "/users",
"menuId": "emng-emp",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Add Employees",
"link": "/addEmployee",
"menuId": "emng-emp-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete Employees",
"link": null,
"menuId": "emng-emp-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Employees",
"link": null,
"menuId": "emng-emp-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Employees",
"link": null,
"menuId": "emng-emp-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Leave Approval",
"link": "/leaveApproval",
"menuId": "emng-lea",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "List Leave Approval",
"link": null,
"menuId": "emng-lea-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Leave Approval",
"link": null,
"menuId": "emng-lea-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Monthly Attendance",
"link": "/monthlyAttendance",
"menuId": "emng-mta",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "List Monthly Attendance",
"link": null,
"menuId": "emng-mta-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Daily Attendance",
"link": "/dailyAttendance",
"menuId": "emng-dla",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "List Daily Attendance",
"link": null,
"menuId": "emng-dla-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "In Out Register",
"link": "/viewInOutRegister",
"menuId": "emng-ior",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "List In Out Register",
"link": null,
"menuId": "emng-ior-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
}
]
},
{
"name": "Payroll Management",
"link": "",
"menuId": "pmng",
"icon": "fa fa-paypal fa-2x",
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Salary Structure Template",
"link": "/overtime",
"menuId": "pmng-ot",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Add Salary Structure Template",
"link": null,
"menuId": "pmng-ot-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List Salary Structure Template",
"link": null,
"menuId": "pmng-ot-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Association of template for Employee",
"link": "",
"menuId": "pmng-bnk",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": " View template for Employee",
"link": null,
"menuId": "pmng-bnk-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "delete template for Employee",
"link": null,
"menuId": "pmng-bnk-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Salary Slip",
"link": "",
"menuId": "pmng-ot",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Employee Profile",
"link": "",
"menuId": "edsh",
"icon": "fa fa-users fa-2x",
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Personal Details",
"link": "",
"menuId": "pmng-dtls",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Attendance",
"link": "",
"menuId": "edsh-emp",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "View Daily Attendance",
"link": null,
"menuId": "edsh-emp-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "View Monthly Attendance",
"link": null,
"menuId": "edsh-emp-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Salary Pacakge Structure",
"link": "",
"menuId": "pmng-bnk",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": " View Salary Pacakge Structure ",
"link": null,
"menuId": "edsh-ler-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": " Pay Slip ",
"link": null,
"menuId": "edsh-ler-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Leave Application",
"link": "/leaveRequest",
"menuId": "edsh-ler",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "Apply Leave ",
"link": null,
"menuId": "edsh-ler-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "View Leave Request",
"link": null,
"menuId": "edsh-ler-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit Leave Request",
"link": null,
"menuId": "edsh-ler-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Shift Timings",
"link": "",
"menuId": "edsh-ior",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "View Shift Timings",
"link": null,
"menuId": "edsh-ior-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Holiday List",
"link": "/holidayList",
"menuId": "hld-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": [
{
"name": "List Holiday",
"link": null,
"menuId": "emp-hld-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
}
]
},
{
"name": "Package",
"link": "/pack",
"menuId": "set-pkg",
"icon": "fa fa-cogs fa-2x",
"desc": null,
"selected": true,
"subMenus": [
{
"name": "Create package",
"link": null,
"menuId": "set-pkg-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete package",
"link": null,
"menuId": "set-pkg-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit package",
"link": null,
"menuId": "set-pkg-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List package",
"link": null,
"menuId": "set-pkg-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
},
{
"name": "Organization",
"link": "/org",
"menuId": "set-org",
"icon": "fa fa-cogs fa-2x",
"desc": null,
"selected": true,
"subMenus": [
{
"name": "Create organization",
"link": null,
"menuId": "set-org-add",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Delete organization",
"link": null,
"menuId": "set-org-del",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "Edit organization",
"link": null,
"menuId": "set-org-edt",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
},
{
"name": "List organization",
"link": null,
"menuId": "set-org-lst",
"icon": null,
"desc": null,
"selected": false,
"subMenus": []
}
]
}
]
}

Use the below link or something similar to first create a Java object class to hold the data
http://www.jsonschema2pojo.org/
The use GsonConverterFactory with Retrofit to convert the object. Below link tells you how to add it
https://futurestud.io/tutorials/retrofit-2-adding-customizing-the-gson-converter

Create Pojo class and implementsSerializable. Use this class to get a response.
try this,
class pojo implements Serializable{
#SerializedName("name")
private String name;
public long getName() {
return name;
}
public void setId(String name) {
this.name = name;
}
}

Related

getting problem in HashMap<String,ArrayList<Model>> , (Creating Comments View in Android )

Receiveg this Json Response
{
"result": "success",
"data": [
{
"comment": "hi",
"addedon": "2019-03-01 09:31:28",
"user_id": "1",
"id": "22",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "hixdh ",
"addedon": "2019-03-01 09:31:32",
"user_id": "1",
"id": "23",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "xy uf",
"addedon": "2019-03-01 09:31:36",
"user_id": "1",
"id": "24",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "cgui ",
"addedon": "2019-03-01 09:31:39",
"user_id": "1",
"id": "25",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "hi",
"addedon": "2019-03-01 09:33:32",
"user_id": "1",
"id": "26",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "fg ",
"addedon": "2019-03-01 09:33:34",
"user_id": "1",
"id": "27",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "chkk hhh",
"addedon": "2019-03-01 09:33:39",
"user_id": "1",
"id": "28",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "yubvcg ",
"addedon": "2019-03-01 09:33:43",
"user_id": "1",
"id": "29",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "ggi ",
"addedon": "2019-03-01 09:33:47",
"user_id": "1",
"id": "30",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "cfg hj",
"addedon": "2019-03-01 09:33:50",
"user_id": "1",
"id": "31",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "vbj",
"addedon": "2019-03-01 09:33:53",
"user_id": "1",
"id": "32",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "hehh",
"addedon": "2019-03-01 11:32:13",
"user_id": "18",
"id": "33",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hhh",
"addedon": "2019-03-01 11:43:26",
"user_id": "18",
"id": "37",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hahahah",
"addedon": "2019-03-01 12:04:14",
"user_id": "18",
"id": "42",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hii",
"addedon": "2019-03-01 12:16:05",
"user_id": "18",
"id": "43",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hou",
"addedon": "2019-03-01 12:16:12",
"user_id": "18",
"id": "44",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hi",
"addedon": "2019-03-01 12:16:28",
"user_id": "18",
"id": "45",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hi",
"addedon": "2019-03-01 12:16:45",
"user_id": "18",
"id": "46",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "hi",
"addedon": "2019-03-01 12:16:52",
"user_id": "18",
"id": "47",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "gg",
"addedon": "2019-03-01 12:17:09",
"user_id": "18",
"id": "48",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "heyy",
"addedon": "2019-03-01 12:31:26",
"user_id": "1",
"id": "49",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "fff",
"addedon": "2019-03-01 12:36:52",
"user_id": "1",
"id": "52",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "hhh",
"addedon": "2019-03-02 00:13:41",
"user_id": "18",
"id": "54",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "jii",
"addedon": "2019-03-02 02:33:55",
"user_id": "1",
"id": "61",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "dsdsdsdsd",
"addedon": "2019-03-03 03:44:33",
"user_id": "1",
"id": "63",
"name": "chitransh",
"photo": "user.png"
}
],
"reply": {
"22": [
{
"comment": "hahaha",
"addedon": "2019-03-02 00:34:50",
"user_id": "18",
"id": "58",
"name": "Test User 3",
"photo": "avatar10.png"
},
{
"comment": "#chitransh heyyy",
"addedon": "2019-03-03 03:44:59",
"user_id": "1",
"id": "65",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "#chitransh heyy test user",
"addedon": "2019-03-03 03:45:23",
"user_id": "1",
"id": "66",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "#chitransh hiw are you",
"addedon": "2019-03-03 04:06:09",
"user_id": "1",
"id": "67",
"name": "chitransh",
"photo": "user.png"
}
],
"23": [
{
"comment": "#chitransh hhhh",
"addedon": "2019-03-02 01:04:58",
"user_id": "18",
"id": "59",
"name": "Test User 3",
"photo": "avatar10.png"
}
],
"24": [],
"25": [],
"26": [],
"27": [],
"28": [],
"29": [],
"30": [],
"31": [
{
"comment": "#chitranshdsdsdsdsd",
"addedon": "2019-03-02 05:07:44",
"user_id": "1",
"id": "62",
"name": "chitransh",
"photo": "user.png"
}
],
"32": [],
"33": [],
"37": [],
"42": [],
"43": [],
"44": [],
"45": [],
"46": [],
"47": [],
"48": [],
"49": [
{
"comment": "chitransh hi",
"addedon": "2019-03-01 12:32:47",
"user_id": "1",
"id": "50",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "chitransh sdff",
"addedon": "2019-03-01 12:33:00",
"user_id": "1",
"id": "51",
"name": "chitransh",
"photo": "user.png"
},
{
"comment": "chitransh hi",
"addedon": "2019-03-01 12:42:59",
"user_id": "1",
"id": "53",
"name": "chitransh",
"photo": "user.png"
}
],
"52": [],
"54": [
{
"comment": "#Test User 3kjj",
"addedon": "2019-03-02 01:20:55",
"user_id": "18",
"id": "60",
"name": "Test User 3",
"photo": "avatar10.png"
}
],
"61": [
{
"comment": "#chitranshdsdsdsdsdsd",
"addedon": "2019-03-03 03:44:40",
"user_id": "1",
"id": "64",
"name": "chitransh",
"photo": "user.png"
}
],
"63": []
}
}
Done with data JSONArray , now working for replies
as you can see in reply JSONArray I will get id from data so I am storing that id in my Map as key ex.
Map<String,Arraylist<ReplyCommentModel>>
so String refers to that id .
now on buttonOnClick in RecyclerView item
I am using this code -- >
viewRepliesButton.setOnClickListener(v -> {
if (collpased){
collpased = false;
replyRecyclerView.setVisibility(View.VISIBLE);
GroupAdapter<ViewHolder> adapter = new GroupAdapter<>();
replyRecyclerView.setAdapter(adapter);
replyRecyclerView.setLayoutManager(new LinearLayoutManager(context));
replyCommentModels = replyModelsMap.get(String.valueOf(model.comment_id));
if(replyCommentModels != null){
Log.e("replComments ","Size" +replyCommentModels.size());
for(ReplyCommentModel replyCommentModel : replyCommentModels){
adapter.add(new ReplyCommentItem(replyCommentModel,context));
}
}
viewRepliesButton.setText("hide");
} else {
collpased = true;
replyRecyclerView.setVisibility(View.GONE);
viewRepliesButton.setText("Tap to view reply");
}
});
but all of the items in map are visible In recyclerView is there some problem in my code?
Since I am passing value of comment id from my adapter item model is the Data key from JSON response you can see above
now I am clicking on the list and passing its id to map to get the array list of that particular id , maybe map is used to do this or there is some other preferable way to do this ?
new in using Map<> with Arraylist tbh , any proper guidance will be appreciated
and I am saving my map as like this
private Map<String,ArrayList<ReplyCommentModel>> replyModelMap = new HashMap<>();
try {
JSONObject obj = new JSONObject(response);
String status = obj.getString("result");
if (status.equals("success")) {
JSONArray jsonArray = obj.getJSONArray("data");
if(model.size() == 0){
fetchComments(jsonArray);
JSONObject replyObject = obj.getJSONObject("reply");
for(int i=0;i<model.size();i++){
JSONArray replyArrays = replyObject.getJSONArray(String.valueOf(model.get(i).comment_id));
for(int j=0;j<replyArrays.length();j++){
JSONObject jsonObject1 = replyArrays.getJSONObject(j);
Integer id = jsonObject1.getInt("id");
String name = jsonObject1.getString("name");
String comment_image = jsonObject1.getString("photo");
Integer user_id = jsonObject1.getInt("user_id");
String comment = jsonObject1.getString("comment");
String added_on = jsonObject1.getString("addedon");
String imageURl = Constant.IMAGE_URL+Constant.COMMENT_USER_IMAGE_URL+comment_image;
replyModel.add(new ReplyCommentModel(comment,name,imageURl,added_on,user_id,id));
}
if(replyModel != null){
replyModelMap.put(String.valueOf(model.get(i).comment_id),replyModel);
}
}
Log.e("ReplyModelMapSize","----> "+replyModelMap.size());
setUpRecyclerview();
}else{
model.clear();
fetchComments(jsonArray);
upDateRecyclerView();
}
}
}catch (Exception e){
e.printStackTrace();
}
Try initialising replyModel list inside the inner for loop, it seems all the items getting added to the same list and the same being added to the with all the keys.Hence resulting the entire list with all the keys.Like this:-
for(int i=0;i<model.size();i++){
JSONArray replyArrays = replyObject.getJSONArray(String.valueOf(model.get(i).comment_id));
//Initialise inside the loop
ArrayList<ReplyCommentModel> replyModel = new ArrayList();
for(int j=0;j<replyArrays.length();j++){
JSONObject jsonObject1 = replyArrays.getJSONObject(j);
Integer id = jsonObject1.getInt("id");
String name = jsonObject1.getString("name");
String comment_image = jsonObject1.getString("photo");
Integer user_id = jsonObject1.getInt("user_id");
String comment = jsonObject1.getString("comment");
String added_on = jsonObject1.getString("addedon");
String imageURl = Constant.IMAGE_URL+Constant.COMMENT_USER_IMAGE_URL+comment_image;
replyModel.add(new ReplyCommentModel(comment,name,imageURl,added_on,user_id,id));
}
if(replyModel != null){
replyModelMap.put(String.valueOf(model.get(i).comment_id),replyModel);
}
}

Expected BEGIN_ARRAY but was BEGIN_OBJECT Retrofit Api call fails

I'm creating an Android project for school. Now i want to recieve data from this API using retrofit: Edamam. I keep getting the error shown in the title of this question.
Here are my classes:
Api.java
public interface Api {
final String BASE_URL = "API URL";
final String APP_ID = "SECRET ID";
final String APP_KEY = "SECRET KEY";
#GET("search")
Call<Hits> getHits(#Query("q") String keyword, #Query("app_id") String app_id, #Query("app_key") String app_key);}
HitsController.java
public class HitsController {
public void getHits(String keyword) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<Hits> call = api.getHits(keyword, Api.APP_ID, Api.APP_KEY);
//the enqueue is async
call.enqueue(new Callback<Hits>() {
#Override
public void onResponse(Call<Hits> call, Response<Hits> response) {
Hits hits = response.body();
Log.d(TAG, "onResponse: " + hits.getCount());
}
#Override
public void onFailure(Call<Hits> call, Throwable t) {
Log.d(TAG, "onFailure: the call failed.");
Log.d(TAG, "onFailure: " + call.request().url().toString());
Log.d(TAG, t.getMessage());
}
});
}
}
JSON preview (Hits with one Hit):
{
"q": "chicken",
"from": 0,
"to": 10,
"params": {
"sane": [],
"q": [
"chicken"
],
"app_key": [
"5b5829870f140360800ce3af3a6b6781"
],
"app_id": [
"0ddbef04"
]
},
"more": true,
"count": 190722,
"hits": [
{
"recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_7bf4a371c6884d809682a72808da7dc2",
"label": "Teriyaki Chicken",
"image": "https://www.edamam.com/web-img/262/262b4353ca25074178ead2a07cdf7dc1.jpg",
"source": "David Lebovitz",
"url": "http://www.davidlebovitz.com/2012/12/chicken-teriyaki-recipe-japanese-farm-food/",
"shareAs": "http://www.edamam.com/recipe/teriyaki-chicken-7bf4a371c6884d809682a72808da7dc2/chicken",
"yield": 6,
"dietLabels": [
"Low-Carb"
],
"healthLabels": [
"Sugar-Conscious",
"Peanut-Free",
"Tree-Nut-Free",
"Alcohol-Free"
],
"cautions": [],
"ingredientLines": [
"1/2 cup (125ml) mirin",
"1/2 cup (125ml) soy sauce",
"One 2-inch (5cm) piece of fresh ginger, peeled and grated",
"2-pounds (900g) boneless chicken thighs (4-8 thighs, depending on size)"
],
"ingredients": [
{
"text": "1/2 cup (125ml) mirin",
"weight": 122.99850757795392
},
{
"text": "1/2 cup (125ml) soy sauce",
"weight": 134.72774670265568
},
{
"text": "One 2-inch (5cm) piece of fresh ginger, peeled and grated",
"weight": 15
},
{
"text": "2-pounds (900g) boneless chicken thighs (4-8 thighs, depending on size)",
"weight": 907.18474
}
],
"calories": 2253.101981306866,
"totalWeight": 1179.9109942806097,
"totalTime": 0,
"totalNutrients": {
"ENERC_KCAL": {
"label": "Energy",
"quantity": 2253.101981306866,
"unit": "kcal"
},
"FAT": {
"label": "Fat",
"quantity": 151.56383347020517,
"unit": "g"
},
"FASAT": {
"label": "Saturated",
"quantity": 41.169838892692944,
"unit": "g"
},
"FATRN": {
"label": "Trans",
"quantity": 0.7711070290000002,
"unit": "g"
},
"FAMS": {
"label": "Monounsaturated",
"quantity": 63.10028137309835,
"unit": "g"
},
"FAPU": {
"label": "Polyunsaturated",
"quantity": 31.82952890962799,
"unit": "g"
},
"CHOCDF": {
"label": "Carbs",
"quantity": 17.72546514133862,
"unit": "g"
},
"FIBTG": {
"label": "Fiber",
"quantity": 1.3778219736212456,
"unit": "g"
},
"SUGAR": {
"label": "Sugars",
"quantity": 0.7939109868106228,
"unit": "g"
},
"PROCNT": {
"label": "Protein",
"quantity": 161.72175016748596,
"unit": "g"
},
"CHOLE": {
"label": "Cholesterol",
"quantity": 889.0410452000001,
"unit": "mg"
},
"NA": {
"label": "Sodium",
"quantity": 8139.824735928436,
"unit": "mg"
},
"CA": {
"label": "Calcium",
"quantity": 116.51301359077408,
"unit": "mg"
},
"MG": {
"label": "Magnesium",
"quantity": 276.82169621464243,
"unit": "mg"
},
"K": {
"label": "Potassium",
"quantity": 2529.722194651041,
"unit": "mg"
},
"FE": {
"label": "Iron",
"quantity": 8.335407066766463,
"unit": "mg"
},
"ZN": {
"label": "Zinc",
"quantity": 12.950414243828696,
"unit": "mg"
},
"P": {
"label": "Phosphorus",
"quantity": 1660.4080117810859,
"unit": "mg"
},
"VITA_RAE": {
"label": "Vitamin A",
"quantity": 208.65249020000002,
"unit": "µg"
},
"VITC": {
"label": "Vitamin C",
"quantity": 0.75,
"unit": "mg"
},
"THIA": {
"label": "Thiamin (B1)",
"quantity": 0.7104550166118764,
"unit": "mg"
},
"RIBF": {
"label": "Riboflavin (B2)",
"quantity": 1.542818655059382,
"unit": "mg"
},
"NIA": {
"label": "Niacin (B3)",
"quantity": 45.028415542590324,
"unit": "mg"
},
"VITB6A": {
"label": "Vitamin B6",
"quantity": 3.3713281129199304,
"unit": "mg"
},
"FOLDFE": {
"label": "Folate equivalent (total)",
"quantity": 47.7274267383718,
"unit": "µg"
},
"FOLFD": {
"label": "Folate (food)",
"quantity": 47.7274267383718,
"unit": "µg"
},
"VITB12": {
"label": "Vitamin B12",
"quantity": 5.6245453880000005,
"unit": "µg"
},
"VITD": {
"label": "Vitamin D",
"quantity": 0.9071847400000002,
"unit": "µg"
},
"TOCPHA": {
"label": "Vitamin E",
"quantity": 1.944087954,
"unit": "mg"
},
"VITK1": {
"label": "Vitamin K",
"quantity": 19.065879540000005,
"unit": "µg"
}
},
"totalDaily": {
"ENERC_KCAL": {
"label": "Energy",
"quantity": 112.6550990653433,
"unit": "%"
},
"FAT": {
"label": "Fat",
"quantity": 233.17512841570027,
"unit": "%"
},
"FASAT": {
"label": "Saturated",
"quantity": 205.8491944634647,
"unit": "%"
},
"CHOCDF": {
"label": "Carbs",
"quantity": 5.908488380446207,
"unit": "%"
},
"FIBTG": {
"label": "Fiber",
"quantity": 5.511287894484982,
"unit": "%"
},
"PROCNT": {
"label": "Protein",
"quantity": 323.44350033497193,
"unit": "%"
},
"CHOLE": {
"label": "Cholesterol",
"quantity": 296.3470150666667,
"unit": "%"
},
"NA": {
"label": "Sodium",
"quantity": 339.1593639970182,
"unit": "%"
},
"CA": {
"label": "Calcium",
"quantity": 11.651301359077408,
"unit": "%"
},
"MG": {
"label": "Magnesium",
"quantity": 65.90992767015297,
"unit": "%"
},
"K": {
"label": "Potassium",
"quantity": 53.823876481937035,
"unit": "%"
},
"FE": {
"label": "Iron",
"quantity": 46.307817037591455,
"unit": "%"
},
"ZN": {
"label": "Zinc",
"quantity": 117.73103858026087,
"unit": "%"
},
"P": {
"label": "Phosphorus",
"quantity": 237.20114454015513,
"unit": "%"
},
"VITA_RAE": {
"label": "Vitamin A",
"quantity": 23.183610022222226,
"unit": "%"
},
"VITC": {
"label": "Vitamin C",
"quantity": 0.8333333333333334,
"unit": "%"
},
"THIA": {
"label": "Thiamin (B1)",
"quantity": 59.204584717656374,
"unit": "%"
},
"RIBF": {
"label": "Riboflavin (B2)",
"quantity": 118.67835808149093,
"unit": "%"
},
"NIA": {
"label": "Niacin (B3)",
"quantity": 281.4275971411895,
"unit": "%"
},
"VITB6A": {
"label": "Vitamin B6",
"quantity": 259.33293176307154,
"unit": "%"
},
"FOLDFE": {
"label": "Folate equivalent (total)",
"quantity": 11.93185668459295,
"unit": "%"
},
"VITB12": {
"label": "Vitamin B12",
"quantity": 234.35605783333335,
"unit": "%"
},
"VITD": {
"label": "Vitamin D",
"quantity": 6.047898266666667,
"unit": "%"
},
"TOCPHA": {
"label": "Vitamin E",
"quantity": 12.96058636,
"unit": "%"
},
"VITK1": {
"label": "Vitamin K",
"quantity": 15.888232950000004,
"unit": "%"
}
},
"digest": [
{
"label": "Fat",
"tag": "FAT",
"schemaOrgTag": "fatContent",
"total": 151.56383347020517,
"hasRDI": true,
"daily": 233.17512841570027,
"unit": "g",
"sub": [
{
"label": "Saturated",
"tag": "FASAT",
"schemaOrgTag": "saturatedFatContent",
"total": 41.169838892692944,
"hasRDI": true,
"daily": 205.8491944634647,
"unit": "g"
},
{
"label": "Trans",
"tag": "FATRN",
"schemaOrgTag": "transFatContent",
"total": 0.7711070290000002,
"hasRDI": false,
"daily": 0,
"unit": "g"
},
{
"label": "Monounsaturated",
"tag": "FAMS",
"schemaOrgTag": null,
"total": 63.10028137309835,
"hasRDI": false,
"daily": 0,
"unit": "g"
},
{
"label": "Polyunsaturated",
"tag": "FAPU",
"schemaOrgTag": null,
"total": 31.82952890962799,
"hasRDI": false,
"daily": 0,
"unit": "g"
}
]
},
{
"label": "Carbs",
"tag": "CHOCDF",
"schemaOrgTag": "carbohydrateContent",
"total": 17.72546514133862,
"hasRDI": true,
"daily": 5.908488380446207,
"unit": "g",
"sub": [
{
"label": "Carbs (net)",
"tag": "CHOCDF.net",
"schemaOrgTag": null,
"total": 16.347643167717376,
"hasRDI": false,
"daily": 0,
"unit": "g"
},
{
"label": "Fiber",
"tag": "FIBTG",
"schemaOrgTag": "fiberContent",
"total": 1.3778219736212456,
"hasRDI": true,
"daily": 5.511287894484982,
"unit": "g"
},
{
"label": "Sugars",
"tag": "SUGAR",
"schemaOrgTag": "sugarContent",
"total": 0.7939109868106228,
"hasRDI": false,
"daily": 0,
"unit": "g"
},
{
"label": "Sugars, added",
"tag": "SUGAR.added",
"schemaOrgTag": null,
"total": 0,
"hasRDI": false,
"daily": 0,
"unit": "g"
}
]
},
{
"label": "Protein",
"tag": "PROCNT",
"schemaOrgTag": "proteinContent",
"total": 161.72175016748596,
"hasRDI": true,
"daily": 323.44350033497193,
"unit": "g"
},
{
"label": "Cholesterol",
"tag": "CHOLE",
"schemaOrgTag": "cholesterolContent",
"total": 889.0410452000001,
"hasRDI": true,
"daily": 296.3470150666667,
"unit": "mg"
},
{
"label": "Sodium",
"tag": "NA",
"schemaOrgTag": "sodiumContent",
"total": 8139.824735928436,
"hasRDI": true,
"daily": 339.1593639970182,
"unit": "mg"
},
{
"label": "Calcium",
"tag": "CA",
"schemaOrgTag": null,
"total": 116.51301359077408,
"hasRDI": true,
"daily": 11.651301359077408,
"unit": "mg"
},
{
"label": "Magnesium",
"tag": "MG",
"schemaOrgTag": null,
"total": 276.82169621464243,
"hasRDI": true,
"daily": 65.90992767015297,
"unit": "mg"
},
{
"label": "Potassium",
"tag": "K",
"schemaOrgTag": null,
"total": 2529.722194651041,
"hasRDI": true,
"daily": 53.823876481937035,
"unit": "mg"
},
{
"label": "Iron",
"tag": "FE",
"schemaOrgTag": null,
"total": 8.335407066766463,
"hasRDI": true,
"daily": 46.307817037591455,
"unit": "mg"
},
{
"label": "Zinc",
"tag": "ZN",
"schemaOrgTag": null,
"total": 12.950414243828696,
"hasRDI": true,
"daily": 117.73103858026087,
"unit": "mg"
},
{
"label": "Phosphorus",
"tag": "P",
"schemaOrgTag": null,
"total": 1660.4080117810859,
"hasRDI": true,
"daily": 237.20114454015513,
"unit": "mg"
},
{
"label": "Vitamin A",
"tag": "VITA_RAE",
"schemaOrgTag": null,
"total": 208.65249020000002,
"hasRDI": true,
"daily": 23.183610022222226,
"unit": "µg"
},
{
"label": "Vitamin C",
"tag": "VITC",
"schemaOrgTag": null,
"total": 0.75,
"hasRDI": true,
"daily": 0.8333333333333334,
"unit": "mg"
},
{
"label": "Thiamin (B1)",
"tag": "THIA",
"schemaOrgTag": null,
"total": 0.7104550166118764,
"hasRDI": true,
"daily": 59.204584717656374,
"unit": "mg"
},
{
"label": "Riboflavin (B2)",
"tag": "RIBF",
"schemaOrgTag": null,
"total": 1.542818655059382,
"hasRDI": true,
"daily": 118.67835808149093,
"unit": "mg"
},
{
"label": "Niacin (B3)",
"tag": "NIA",
"schemaOrgTag": null,
"total": 45.028415542590324,
"hasRDI": true,
"daily": 281.4275971411895,
"unit": "mg"
},
{
"label": "Vitamin B6",
"tag": "VITB6A",
"schemaOrgTag": null,
"total": 3.3713281129199304,
"hasRDI": true,
"daily": 259.33293176307154,
"unit": "mg"
},
{
"label": "Folate equivalent (total)",
"tag": "FOLDFE",
"schemaOrgTag": null,
"total": 47.7274267383718,
"hasRDI": true,
"daily": 11.93185668459295,
"unit": "µg"
},
{
"label": "Folate (food)",
"tag": "FOLFD",
"schemaOrgTag": null,
"total": 47.7274267383718,
"hasRDI": false,
"daily": 0,
"unit": "µg"
},
{
"label": "Folic acid",
"tag": "FOLAC",
"schemaOrgTag": null,
"total": 0,
"hasRDI": false,
"daily": 0,
"unit": "µg"
},
{
"label": "Vitamin B12",
"tag": "VITB12",
"schemaOrgTag": null,
"total": 5.6245453880000005,
"hasRDI": true,
"daily": 234.35605783333335,
"unit": "µg"
},
{
"label": "Vitamin D",
"tag": "VITD",
"schemaOrgTag": null,
"total": 0.9071847400000002,
"hasRDI": true,
"daily": 6.047898266666667,
"unit": "µg"
},
{
"label": "Vitamin E",
"tag": "TOCPHA",
"schemaOrgTag": null,
"total": 1.944087954,
"hasRDI": true,
"daily": 12.96058636,
"unit": "mg"
},
{
"label": "Vitamin K",
"tag": "VITK1",
"schemaOrgTag": null,
"total": 19.065879540000005,
"hasRDI": true,
"daily": 15.888232950000004,
"unit": "µg"
}
]
},
"bookmarked": false,
"bought": false
},
As you can see a lot of model classes are needed:
preview classes
I am clueless, I went through every other post but can't seem to find an answer for my problem...
I hope that someone is able to help me!
Thanks in advance :)
EDIT: POSTED THE HITS CLASS
public class Hits {
private String q;
private int from;
private int to;
private String[][] params;
private int count;
private boolean more;
private Hit[] hits;
public Hits(String q, int from, int to, String[][] params, int count, boolean more, Hit[] hits) {
this.q = q;
this.from = from;
this.to = to;
this.params = params;
this.count = count;
this.more = more;
this.hits = hits;
}
public String getQ() {
return q;
}
public int getFrom() {
return from;
}
public int getTo() {
return to;
}
public String[][] getParams() {
return params;
}
public int getCount() {
return count;
}
public boolean isMore() {
return more;
}
public Hit[] getHits() {
return hits;
}
}
You need to get configure retrofit to get only a List of Hits, that is List<Hits>
but its much easier if you created a Java bean which will contain the list of Hits inside, just like the Json response its a object that has a array inside.
For example you have a Example class which has a List<Hits> hits inside
public class Example{
#SerializedName("hits")
private List<Hits> hits;
// optionally you can add the other fields also (not mandatory)
// set getters and setters here
and then you need to modify your Retrofit interface to return a Example object which will contain the Hits
#GET("search")
Call<Example> getExample(#Query("q") String keyword, #Query("app_id") String app_id, #Query("app_key") String app_key);}
and the implementation also
Call<Example> call = api.getHits(keyword, Api.APP_ID, Api.APP_KEY);
//the enqueue is async
call.enqueue(new Callback<Hits>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
Hits hits = response.body();
Log.d(TAG, "onResponse: " + response.getHits().size());
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
}
});

Elasticsearch High Level Rest Client Java sorting not working properly

I am pretty new with Elasticsearch High Level Rest Client (Java).
I have a very simple query which lists all records, but it seems sorting is not working properly.
Some of the fields are text types, so I needed to set fielddata to true.
Update:
Thanks Andrei for the solution.
I need to add another field which is an array of objects user.groups
I added .keyword to the mapping fields (text) which are sortable.
But I am getting unexpected results.
Example:
...
"groups": [
{"name", "ECPay", ... },
{"name", "Abangers", ... }
]
...
Based from the output (below), if there are two group items ECPay and Abangers... using user.groups.name.keyword sorting will consider Abangers.
I would like to consider the first element of user.groups array as a basis of the sort.
Based from the example (above), tt will base the sort with ECPay since it is the first element of the array.
To understand the problem (updated), let us check the search result (sort) below.
Search Result (Output):
{
"took": 18,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 74,
"max_score": null,
"hits": [
{
"_index": "acme_users",
"_type": "user",
"_id": "5",
"_score": null,
"_source": {
"name": "Ericsson Joseph Sultan Atutuli",
"country": "",
"uuid": "5",
"userId": 5,
"email": "ejsultanatutuli#gmail.com",
"deletedInd": false,
"groups": [
{
"name": "ECPay",
"id": 2
},
{
"name": "Abangers",
"id": 4
}
],
"company": ""
},
"sort": [
"Abangers"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "54",
"_score": null,
"_source": {
"name": "Florentina Atutuli",
"country": null,
"uuid": "54",
"userId": 54,
"email": "florentina.atutuli#gmail.com",
"deletedInd": false,
"groups": [
{
"name": "Abangers",
"id": 4
},
{
"name": "Test Group",
"id": 5
}
],
"company": null
},
"sort": [
"Abangers"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "37",
"_score": null,
"_source": {
"name": "dsfsdfsdf",
"country": null,
"uuid": "37",
"userId": 37,
"email": "asdf#sdf.com",
"deletedInd": false,
"groups": [
{
"name": "Abangers",
"id": 4
},
{
"name": "Test Group",
"id": 5
}
],
"company": null
},
"sort": [
"Abangers"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "3",
"_score": null,
"_source": {
"name": "Erick Atutuli",
"country": "Philippines",
"email": "erickatutuli#pakyas.com",
"userId": 3,
"uuid": "d8f4ab43-d33e-4a82-a08b-eb73342a0546",
"groups": [
{
"name": "ECPay",
"id": 2
},
{
"name": "Abangers",
"id": 4
}
],
"deletedInd": false,
"company": "Hotlegs Incorporated"
},
"sort": [
"Abangers"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "34",
"_score": null,
"_source": {
"name": "Chun-Li",
"country": null,
"email": "chunli#pakyas.com",
"uuid": "34",
"userId": 34,
"deletedInd": false,
"groups": [
{
"name": "Customers AU",
"id": 1
}
],
"company": null
},
"sort": [
"Customers AU"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "57",
"_score": null,
"_source": {
"name": "Eddy Bear",
"country": "US",
"email": "eddybear#pakyas.com",
"uuid": "57",
"userId": 57,
"deletedInd": false,
"groups": [
{
"name": "Customers AU",
"id": 1
}
],
"company": "Jollibee"
},
"sort": [
"Customers AU"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "42",
"_score": null,
"_source": {
"name": "Alfredo Pitik Mingaw",
"country": "",
"email": "akomykel#gmail.com",
"userId": 42,
"uuid": "42",
"deletedInd": false,
"groups": [
{
"name": "ECPay",
"id": 2
}
],
"company": ""
},
"sort": [
"ECPay"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "20",
"_score": null,
"_source": {
"name": "test",
"country": "Åland Islands",
"userId": 20,
"email": "test102#email.com",
"uuid": "20",
"groups": [
{
"name": "ECPay",
"id": 2
}
],
"deletedInd": false,
"company": "test"
},
"sort": [
"ECPay"
]
},
...
]
}
}
Now I added keyword field in the user mapping:
...
"groups": {
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
...
Make text fields sortable, removed fielddata and added keywords
http://localhost:9200/acme_users/_mapping/user
{
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"company": {
"type": "text",
"fielddata": true
},
"country": {
"type": "text",
"fielddata": true
},
"groups": {
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"email": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
The query below is generated from my Java application (Spring).
This is a very simple case wherein I just sort the results into name ascending order.
Query
Added .keyword to the sorting field. In the sample below... it will sort using groups.name.keyword which was originally groups.name
http://localhost:9200/acme_users/user/_search
{
"from" : 0,
"size" : 15,
"query" : {
"match_all" : {
"boost" : 1.0
}
},
"sort" : [
{
"groups.name.keyword" : {
"order" : "asc"
}
}
]
}
Original Problem:
But my problem now is, it seems ES sort does not work properly. The results changes when I change the order from asc to desc (vice versa).
Though the results changes, it seems that the names (result) is not sorting properly (a-z) or (z-a).
Seems that it is getting the last part of name and using it as the basis for the sort. I would like to base it on the first character value of name.
Original Search Result:
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 73,
"max_score": null,
"hits": [
{
"_index": "acme_users",
"_type": "user",
"_id": "22",
"_score": null,
"_source": {
"name": "Popeye Partner 01",
"country": null,
"userId": 22,
"email": "popeye_partner_01#kugmo.com",
"uuid": "22",
"deletedInd": false,
"company": null
},
"sort": [
"01"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "24",
"_score": null,
"_source": {
"name": "Dummy User 01",
"country": null,
"userId": 24,
"email": "dummy#dummy.com",
"uuid": "24",
"deletedInd": false,
"company": null
},
"sort": [
"01"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "23",
"_score": null,
"_source": {
"name": "Popeye Partner 02",
"country": null,
"userId": 23,
"email": "popeye_partner_02#kugmo.com",
"uuid": "23",
"deletedInd": false,
"company": null
},
"sort": [
"02"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "25",
"_score": null,
"_source": {
"name": "RT Administrator",
"country": null,
"userId": 25,
"email": "rt_administrator#kugmo.com",
"uuid": "25",
"deletedInd": false,
"company": null
},
"sort": [
"administrator"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "48",
"_score": null,
"_source": {
"name": "John Patrick Abnoy",
"country": null,
"userId": 48,
"email": "patrickabnoy#gmail.com",
"uuid": "48",
"deletedInd": false,
"company": null
},
"sort": [
"abnoy"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "5",
"_score": null,
"_source": {
"name": "Ericsson John Santol Atutuli",
"country": "",
"uuid": "5",
"userId": 5,
"email": "ejsantolatutuli#gmail.com",
"deletedInd": false,
"company": ""
},
"sort": [
"atutuli"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "54",
"_score": null,
"_source": {
"name": "Florentina Atutuli",
"country": null,
"uuid": "54",
"userId": 54,
"email": "florentina.atutuli#gmail.com",
"deletedInd": false,
"company": null
},
"sort": [
"atutuli"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "49",
"_score": null,
"_source": {
"name": "Laarnie Santol Atutuli",
"country": "",
"email": "lmsantolatutuli#gmail.com",
"userId": 49,
"uuid": "49",
"deletedInd": false,
"company": ""
},
"sort": [
"atutuli"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "3",
"_score": null,
"_source": {
"name": "Eric Atutuli",
"country": "Philippines",
"uuid": "d8f4ab43-d33e-4a82-a08b-eb73342a0546",
"userId": 3,
"email": "ericatutuli#kugmo.com",
"deletedInd": false,
"company": "Hotlegs Incorporated"
},
"sort": [
"atutuli"
]
},
{
"_index": "acme_users",
"_type": "user",
"_id": "29",
"_score": null,
"_source": {
"name": "Auberto Matulis",
"country": null,
"userId": 29,
"email": "bert.matulis#gmail.com",
"uuid": "29",
"deletedInd": false,
"company": null
},
"sort": [
"auberto"
]
}
]
}
}
Thanks!
name is a text field which means it is analyzed. Analyzed means it's split into tokens. If Popeye Partner 01 is split into popeye, partner, 01 which field you want to use for sorting? Probably none of them, since you want the sort to happen on the original text. For this to happen, add a sub-field to your name field
{
"name": {
"type" "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
and make it keyword then in your query use that for sorting:
"sort" : [
{
"name.keyword" : {
"order" : "asc"
}
}
]
We ran into the same issue and then we looked at the mapping which we created at the time of indexCreation and we observed a couple of things.
All the fields which always have one word as the value should be changed to keyword so we dont need to append .keyword in all the fields names(dont want to mantain schema on client side to append .keyword) or add "fielddata": true( avoid this as much as possible, because it takes up your heap mem)
"type":"keyword"
All the values which are defined as text but actually they are number, so we changed to either long or scaled_float. This helped us in sorting and aggregation.
"type":"long"
OR
"type": "scaled_float",
"scaling_factor": 100

How can I extract the array of hashmap object from a hashmap object?

{
"errorCode": 200,
"opMessage": {
"personalDetails": {
"dob": {
"mm": 2,
"dd": 2,
"yyyy": 1975
},
"name": {
"fname": "sai gampa",
"lName": "krishna"
},
"maritalStatus": "Single",
"ssn": "123-45-7777"
},
"id": "0101",
"contactDetails": {
"address": [
{
"isPrimary": true,
"id": "HOME;2017-06-30",
"type": "Home",
"addr": {
"country": "USA",
"addr2": "W 24th St",
"addr1": "518",
"city": "New York",
"postalCode": "11122",
"state": "NY"
}
},
{
"isPrimary": false,
"id": "BUSN;2017-07-04",
"type": "Work",
"addr": {
"country": "USA",
"addr2": "Agsuaiajs",
"addr1": "Qwertyy",
"city": "Shshshsjsj",
"postalCode": "71899",
"state": "CO"
}
}
],
"bestWayToContact": "Phone",
"ph": [
{
"isPrimary": false,
"num": "666-666-6666",
"id": "Work",
"type": "Work"
},
{
"isPrimary": false,
"num": "444-444-4444",
"id": "Cell",
"type": "Cell"
},
{
"isPrimary": true,
"num": "111-111-1111",
"id": "Home",
"type": "Home"
}
],
"eMail": [
{
"isPrimary": true,
"id": "HOME",
"addr": "Shyam#gmail.con"
}
]
}
}
}
HashMap has a method called entrySet(). With entrySet() you can get all the entries in the hashmap.

how to extract value from the json response which is under array and array is under object

enter image description here JSON Response:-
{
"hotelogix": {
"version": "1.0",
"datetime": "2017-01-17T11:37:58",
"response": {
"status": {
"code": 0,
"message": "success"
},
"nightAuditDate": "2015-04-15",
"lastUpdatedOn": "2017-01-17 11:05:40",
"isUpdated": true,
"totalRecords": "2",
"totalPages": 1,
"bookings": [
{
"isGroup": false,
"group": null,
"id": "gbighAuuug||",
"mainId": "gbighAuuug||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"adult": 2,
"child": 0,
"infant": 0,
"code": "12281852",
"reservationStatus": "RESERVE",
"businessSourcesId": null,
"source": "PMS",
"preference": "",
"roomStays": [
{
"date": "2015-04-15",
"roomTypeId": "gb_BTEs|",
"roomTypeName": "old age rooms",
"roomTypeCode": "CLSccc",
"roomId": "0",
"roomName": "",
"rateId": "gw||",
"rateName": "Seasonal Rate",
"amount": "600.000000",
"tax": "0.000000",
"discountAmount": "0.000000"
}
],
"guestStays": [
{
"id": "h2H4TkT2Bw||",
"mainId": "h2H4TkT2Bw||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": true,
"isChargeSharer": true,
"type": "Adult",
"guestDetails": {
"id": "gsgPzJITYA||",
"code": "P949",
"salutation": null,
"fName": "Neha",
"lName": "Sharma",
"email": "neha#hotelogix.com",
"phoneNo": "55887799",
"mobileNo": "",
"gender": null,
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
}
},
{
"id": "h2H4TkT2Ag||",
"mainId": "h2H4TkT2Ag||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": false,
"isChargeSharer": false,
"type": "Adult",
"guestDetails": {
"id": "gsgPzJITYg||",
"code": "P951",
"salutation": null,
"fName": "Mayajhanti",
"lName": "Jha",
"email": "mayanti#hotelogix.com",
"phoneNo": "01158988888",
"mobileNo": "99680480558",
"gender": "Male",
"nationality": "US",
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "D-996, Cross Road",
"country": "US",
"state": "CA",
"city": "Los Angeles",
"zip": "325215",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": [
{
"name": "Id Proof",
"url": "c://Users//mukesh//Desktop//abc.png"
},
{
"name": "Id Proof",
"url": "c://Users//mukesh//Desktop//abc.png"
}
]
}
}
],
"payments": [],
"otherCharges": [],
"addons": [],
"isHoldTill": false,
"releaseDate": "0000-00-00 00:00:00"
},
{
"isGroup": true,
"group": {
"id": "h2AIqHf1",
"mainId": "h2AIqHf1",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"code": "G 0117433",
"groupStatus": "RESERVE",
"businessSourcesId": null,
"source": "",
"preference": "",
"ownerType": "Guest",
"owner": {
"id": "gsgPzf2HQw||",
"code": "P957",
"salutation": null,
"fName": "juna",
"lName": "mishra",
"email": "juna#hotelogix.com",
"phoneNo": "",
"mobileNo": "8802640811",
"gender": null,
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
},
"payTerm": 2,
"payments": [],
"otherCharges": [],
"groupLeader": []
},
"id": "gbihNuZBbA||",
"mainId": "gbihNuZBbA||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"adult": 1,
"child": 0,
"infant": 0,
"code": "01171859",
"reservationStatus": "RESERVE",
"businessSourcesId": null,
"source": "PMS",
"preference": "",
"roomStays": [
{
"date": "2015-04-15",
"roomTypeId": "gb_BTEs|",
"roomTypeName": "old age rooms",
"roomTypeCode": "CLSccc",
"roomId": "0",
"roomName": "",
"rateId": "gw||",
"rateName": "Seasonal Rate",
"amount": "500.000000",
"tax": "0.000000",
"discountAmount": "0.000000"
}
],
"guestStays": [
{
"id": "h2ANlxcGFg||",
"mainId": "h2ANlxcGFg||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": true,
"isChargeSharer": true,
"type": "Adult",
"guestDetails": {
"id": "gsgPzf2HQg||",
"code": "P958",
"salutation": null,
"fName": "mina",
"lName": "sharma",
"email": "",
"phoneNo": "545487875454",
"mobileNo": "",
"gender": "Male",
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
}
}
],
"payments": [],
"otherCharges": [],
"addons": [],
"isHoldTill": false,
"releaseDate": "0000-00-00 00:00:00"
}
]
},
{
"xyx": {
"version": "1.0",
"datetime": "2016-12-13T05:27:08",
"response": {
"status": {
"code": 0,
"message": "success"
},
"hotels": [
{
"id": 6209,
"userTypes": [
{
"id": "UXjk0A||",
"title": "manager",
"status": "Active"
},
{
"id": "UJlhsA||",
"title": "test23",
"status": "Active"
},
{
"id": "UJll-Q||",
"title": "march",
"status": "Active"
},
{
"id": "UJlnNA||",
"title": "ajay mishra",
"status": "Active"
},
{
"id": "UJlnMw||",
"title": "prime",
"status": "Active"
},
{
"id": "UJlnPg||",
"title": "rr",
"status": "Active"
},
{
"id": "UJlnPw||",
"title": "xman",
"status": "Active"
},
{
"id": "UJloKg||",
"title": "sdd",
"status": "Active"
},
{
"id": "UJloKQ||",
"title": "tst1",
"status": "Active"
},
{
"id": "UJloLg||",
"title": "test2",
"status": "Active"
},
{
"id": "UJloLw||",
"title": "test3",
"status": "Active"
},
{
"id": "UJlpoA||",
"title": "kk",
"status": "Active"
},
{
"id": "UJlpqQ||",
"title": "shantanu manager",
"status": "Active"
},
{
"id": "UJhGcA||",
"title": "elbo",
"status": "Active"
}
]
}
]
},
"request": {
"method": "getusertypes",
"key": "02w7TK3e-0Ccoyo",
"data": {
"hotels": [
{
"id": 6209
}
]
}
}
}
}
My code:-
String getusertypestitlestring = jsonResult.getJSONObject("xyz").getJSONObject("response").getJSONArray("hotels").getJSONArray(0).getString(1);
:: i want to get userTypes>> title
:: i want to get bookings >> group >> code
Try this:
JSONArray userTypesArray = jsonResult.getJSONObject("xyx").getJSONObject("response").getJSONArray("hotels").getJSONObject(0).getJSONArray("userTypes");
for(int i =0 ; i< userTypesArray.length(); i++){
JSONObject userType = userTypesArray.getJSONObject(i);
System.out.println(userType.get("title"));
}
String getusertypestitlestring = jsonResult.getJSONObject("xyz").getJSONObject("response").getJSONArray("hotels").getJSONArray(0).getString(1);
Here it is not xyz, that is xyx
Make pojo of each Json Object in your Json String.
For Ex:
Make class POJO:
public class POJO {
XYX xyx;
public XYX getXyx() {
return xyx;
}
public void setXyx(XYX xyx) {
this.xyx = xyx;
}
}
Make class XYX:
public class XYX implements Serializable{
String version;
String datetime;
Response response;
Request request;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public Request getRequest() {
return request;
}
public void setRequest(Request request) {
this.request = request;
}
}
Make class Response:
class Response {
Status status;
List<Hotels> hotels;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public List<Hotels> getHotels() {
return hotels;
}
public void setHotels(List<Hotels> hotels) {
this.hotels = hotels;
}
}
Make Class Request :
class Request {
String method;
String key;
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
and for List
Make class Hotels:
class Hotels {
String id;
List<UserTypes> userTypes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<UserTypes> getUserTypes() {
return userTypes;
}
public void setUserTypes(List<UserTypes> userTypes) {
this.userTypes = userTypes;
}
}
and make all other pojo classes and use Gson library to set data in your pojos :
POJO pojo = new Gson().fromJson(jsonResponse,POJO.class);
And read Data from pojo :
System.out.println(pojo.getXyx().getDatetime());
System.out.println(pojo.getXyx().getRequest().getKey());
System.out.println(pojo.getXyx().getResponse().getHotels().get(0).getUserTypes().get(0).getTitle());
You can easily use GSON instead of JSON. It's more comfortable to work with the GSON objects. More input is available at:
https://google.github.io/gson/apidocs/com/google/gson/Gson.html

Categories