Skip to content

Instantly share code, notes, and snippets.

@devmnj
Created July 8, 2018 07:22
Show Gist options
  • Save devmnj/1a06d1758aacc503fe271448a4ecc0e7 to your computer and use it in GitHub Desktop.
Save devmnj/1a06d1758aacc503fe271448a4ecc0e7 to your computer and use it in GitHub Desktop.
Deserialize JSON string in Android Studio with HASH MAP
//The JSON FILE
{
"users": [
{
"id": "1087",
"name": "Abhishek Saini",
"email": "[email protected]",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "1088",
"name": "Gourav",
"email": "[email protected]",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
//Load data from JSON FILE
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("users_list.jason");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
//On create code
ListView listView = (ListView) findViewById(R.id.list);
try {
// get JSONObject from JSON file
JSONObject obj = new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray = obj.getJSONArray("users");
// implement for loop for getting users list data
List<Map<String,String>> list =new ArrayList <Map<String,String>>();
for (int i = 0; i < userArray.length(); i++) {
Map<String,String> map=new HashMap<String, String>() ;
JSONObject userDetail = userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
map.put("name",userDetail.getString("name"));
// create a object for getting contact data from JSONObject
JSONObject contact = userDetail.getJSONObject("contact");
// fetch mobile number and store it in arraylist
map.put("mobile",contact.getString("mobile"));
list.add(map);
}
String []col={"name","mobile"};
int []view={R.id.textView,R.id.MobileView};
SimpleAdapter simpleAdapter=new SimpleAdapter(this,list,R.layout.activity_listview,col,view);
listView.setAdapter(simpleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment