Reputation: 533
I have this JSON string.
{
"drtest": {
"password":"dr123",
"presence": {
"lastSeen":1485992132269,
"status":"offline"
},
"role":"Doctor",
"speciality":"Physiotherapist",
"token":"f80ve0sY6Ak:APA91bGLPlmy7b_iyqtW9ioG11TOx3xTB9BJgb1vvBK4YRo-28DyXWydg476TvjzaxyNB3kTTMn0BycEDm9UJHAPeoWzV-vFrwN46hg-GKSI6DH1s9zrH8h834c2whEdr12XqWN-4jrs"
},
"patient": {
"password":"pat123",
"presence": {
"lastSeen":1486046501150,
"status":"online"
},
"role":"Patient",
"token":"f80ve0sY6Ak:APA91bGLPlmy7b_iyqtW9ioG11TOx3xTB9BJgb1vvBK4YRo-28DyXWydg476TvjzaxyNB3kTTMn0BycEDm9UJHAPeoWzV-vFrwN46hg-GKSI6DH1s9zrH8h834c2whEdr12XqWN-4jrs"
}
}
Firstly I was keeping the track of doctor role, but now I have to keep track on speciality as well. However I am trying the code which supposed to work correct but it is not working as expected.
As you can see only one entity has speciality data and other does not contain the field of speciality. How can I parse speciality data if it is there and ignore if there's no speciality field in the JSON?
I am using this code :
try {
contactList.clear();
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
while (i.hasNext()) {
key = i.next().toString();
JSONObject singleUser = (JSONObject) obj.get(key);
String role = singleUser.get("role").toString();
JSONObject singleUser2 = (JSONObject) obj.get(key);
String tpesu= singleUser2.getString("speciality");
// no success here? need help want this value...
Log.e("specialittyyyyyyy",tpesu+"");
JSONObject presence = singleUser.getJSONObject("presence");
String status = presence.getString("status");
if (!key.equals(UserDetails.username)) {
if (role.equals("Doctor")) {
HashMap<String, String> docs = new HashMap<>();
docs.put("name", key);
docs.put("status", status);
Log.e("status ", status + "");
contactList.add(docs);
}
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 1
Views: 1335
Reputation: 17140
Your singleUser
& singleUser2
json objects are the same (drtest) since you are retrieving them by referencing them by the same key
value. Instead let singleUser2
be retrieved by the next available key (singleUser2key=...
in the example below)
JSONObject obj = new JSONObject("dd");
Iterator i = obj.keys();
String key = "";
while (i.hasNext()) {
key = i.next().toString();
String singleUser2key = i.next().toString();
JSONObject singleUser = (JSONObject) obj.get(key);
String role = singleUser.get("role").toString();
JSONObject singleUser2 = (JSONObject) obj.get(singleUser2key);
String tpesu= singleUser2.getString("speciality");
// no success here ??? need help want this value...
Log.e("specialittyyyyyyy",tpesu+"");
Upvotes: 0
Reputation: 1521
You can use the "has" function. i.e. if (singleUser2.has("speciality")) ...
Upvotes: 1
Reputation: 1343
Enclose singleUser as such to avoid format or null pointer exceptions
if(singleUser2.has("speciality")) {
tpesu = singleUser2.getString("speciality");
}
declare the string tpesu globally.
Upvotes: 3