-3

I'm developing an android application where I'm reading results from an online database to a string of this form:

{"success":1,"innerResult":[{"username":"raafat","password":"123"}]}

I need to be able to read only the username and password values even when I have more than one result. For example i need an array of usernames returned and another array of passwords.

I tried splitting the string but it's confusing when you have many entries.

Rabah Hamzah
  • 125
  • 1
  • 9

2 Answers2

3

Your string is in Json format, you can try something like that :

try{
    JSONObject yourObject = new JSONObject(yourString);
    int resultCode = yourObject.getInt("success");
    JSONArray innerResult = yourObject.getJSONArray("innerResult");
    //you'll need to iterate through your array then
    List<String> userNames = new ArrayList<>();
    List<String> passwords = new ArrayList<>();
    for(int i =0 ; i < innerResult.length() ; i++){
        JSONObject user = innerResult.getJSONObject(i);
        userNames.add(user.getString("username"));
        passwords.add(user.getString("password"));
    }
}catch(JSONException e){
   e.printStackTrace();
}

Or you can use library like GSon !

Bastien Viatge
  • 315
  • 3
  • 15
2

Use Gson.

Step 1: Creating bean of response data. In your case you want details of Username and Password.

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Step 2: Parse JSON response and using Gson convert it to your desired bean.

String response = "{\"success\":1,\"innerResult\":[{\"username\":\"raafat\",\"password\":\"123\"}]}";
JSONObject jsonObject = new JSONObject(response);

if(jsonObject.has("innerResult")){
   Type type = new TypeToken<List<User>>() {}.getType();
   List<User> listUsers = new Gson().fromJson(jsonObject.getJSONArray("innerResult").toString(), type);
}
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67