Reputation: 240
Code
//Just assume this Json is perfectly fine. Taken from a web services
this.jsonData = [ { "mobile": "12345", "msg": "Test Message", "id": "28991", "name": "Test User", "senttime": "2019-07-05 14:36:24", "company": "My Company" }]
public static HashMap<String, String> map_id_to_mobile = new HashMap<String, String>();
public static HashMap<String, String> map_id_to_name = new HashMap<String, String>();
public static HashMap<String, String> map_id_to_message = new HashMap<String, String>();
public static HashMap<String, String> map_id_to_company = new HashMap<String, String>();
JSONArray JA = new JSONArray(this.jsonData);
int i = 0;
while (i < JA.length()) {
JSONObject JO = (JSONObject) JA.get(i);
map_id_to_mobile.put(JO.get("id").toString(), JO.get("mobile").toString() );
map_id_to_name.put(JO.get("id").toString(), JO.get("name").toString() );
map_id_to_message.put(JO.get("id").toString(), JO.get("msg").toString() );
map_id_to_company.put(JO.get("id").toString(), JO.get("company").toString() );
}
I am not satisfied with this code because of the the four different arrays. I just wanted to use a php like multi-dimensional arrays where i could just do the following.
smsData[JO.get('id')] = array('mobile'=> JO.get('mobile).toString(), 'msg' => JO.get('msg').toString(), 'company' => JO.get('company').toString();
The reason for this is the ease of accessing the data when the array becomes more multi dimensional. Any comments? Any reference with similar idea pls let me know... been scouring stackoverflow but not satisfied with the answers... Please help.
Upvotes: 1
Views: 72
Reputation: 1637
public Map<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
JSONArray JA = new JSONArray(this.jsonData);
int i = 0;
while (i < JA.length()) {
JSONObject JO = (JSONObject) JA.get(i);
Map<String, String> innerMap = new HashMap<String, String>();
innerMap.put("mobile", JO.get("mobile").toString());
innerMap.put("msg", JO.get("msg").toString());
innerMap.put("company", JO.get("company").toString());
innerMap.put("name", JO.get("name").toString());
map.put(JO.get("id").toString(), innerMap);
}
Upvotes: 1