user6299584
user6299584

Reputation:

Access a JSON Object inside another JSON Object

I have a JSON like this in my Android app :

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtZWhkaS5hZ291emFsQGdtYWlsLmNvbSIsImV4cCI6MTQ2ODU1NTU4MjQ5MX0.A6-xNIZdbPv9mpjLO9jnnfbAeq1y-DC08SBUt2xBnYo",
    "expires": 1468555582491,
    "user": {
        "imageURL": "http://app.com/images/null",
        "email": "[email protected]",
        "firstname": "mister",
        "lastname": "lalalala",
        "password": "$2a$10$VDGtxjz9w7f170Wc66OJi.1T",
        "id": "c19349c4044d34333",
        "language": "EN",
        "createdAt": "2015-07-07T14:15:54.000Z",
        "updatedAt": "2016-05-06T08:25:20.000Z"
    }
}

I can access to the "token" like this :

String json = new String(bytes);
                JSONObject jsonObj = null;

     try {
            jsonObj = new JSONObject(json);
          } catch (JSONException e) {
             e.printStackTrace();
          }

Log.d("debug", "TOKEN : " + jsonObj.getString("token"));

But I don't know how to get the user email or firstname for example. How can I do that ?

Thanks

Upvotes: 3

Views: 3731

Answers (3)

Anuj Sharma
Anuj Sharma

Reputation: 4324

You have to use JsonObject

String yourJson = new String(your json data);
        JSONObject userObj = null;
        try {
            JSONObject jsonObj = new JSONObject(yourJson);
            userObj = jsonObj.getJSONObject("user");
            String email = userObj.getString("email");
            String firstname = userObj.getString("firstname");
            System.out.println("Email-> " + email);
            System.out.println("Firstname-> " + firstname);


        } catch (JSONException e) {
            e.printStackTrace();
        }

Or you can use

Gson Format

plugin in android studio

Copy and paste your json into file and it will create its getter and setter automatically.

UserModel.Java

public class UserModel {

    private String token;
    private long expires;

    private UserBean user;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public long getExpires() {
        return expires;
    }

    public void setExpires(long expires) {
        this.expires = expires;
    }

    public UserBean getUser() {
        return user;
    }

    public void setUser(UserBean user) {
        this.user = user;
    }

    public static class UserBean {
        private String imageURL;
        private String email;
        private String firstname;
        private String lastname;
        private String password;
        private String id;
        private String language;
        private String createdAt;
        private String updatedAt;

        public String getImageURL() {
            return imageURL;
        }

        public void setImageURL(String imageURL) {
            this.imageURL = imageURL;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getFirstname() {
            return firstname;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }

        public String getLastname() {
            return lastname;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getLanguage() {
            return language;
        }

        public void setLanguage(String language) {
            this.language = language;
        }

        public String getCreatedAt() {
            return createdAt;
        }

        public void setCreatedAt(String createdAt) {
            this.createdAt = createdAt;
        }

        public String getUpdatedAt() {
            return updatedAt;
        }

        public void setUpdatedAt(String updatedAt) {
            this.updatedAt = updatedAt;
        }
    }
}

When you got Json String just parse it to Model class using [Gson][2] object and get all your values like this.

Gson gson = new Gson();
        UserModel obj = gson.fromJson(yourJson,UserModel.class);
        String email = obj.getUser().getEmail();
        String firstName = obj.getUser().getFirstname();
        String token = obj.getToken();

Upvotes: 0

roarster
roarster

Reputation: 4086

Use getJSONObject(String name) to get the "user" object and then use getString(String name) on the resulting JSONObject:

String json = new String(bytes);
JSONObject jsonObj = null;
JSONObject userObj = null;

     try {
            jsonObj = new JSONObject(json);
            userObj = jsonObj.getJSONObject("user");
          } catch (JSONException e) {
             e.printStackTrace();
          }


Log.d("debug", "firstname : " + userObj.getString("firstname"));

P.S

If you want to be really proper about deserializing JSON, I recommend you start using POJOs. This way you can turn the JSON string into actual Java objects that you can interact with. For example, using the JSON library GSON:

Response Class:

public class Response {
  public String token;
  public Long expires;
  public User user;
}

User class:

public class User {
  public String imageURL;
  public String email;
  public String firstname;
  public String lastname;
  public String password;
  public String id;
  public String language;
  public Date createdAt;
  public Date updatedAt;
}

Deserialization code:

Gson gson = new Gson();

Response response = gson.fromJson( jsonString, Response.class );

User user = response.user;

Log.d("debug", "firstname : " + user.firstname;

Upvotes: 4

Shree Krishna
Shree Krishna

Reputation: 8562

Simply do,

  String email = jsonObj.getJSONObject("user").getString("email");

Upvotes: 1

Related Questions