Search code examples
javajsonpojo

What should be the Java object for this JSON String?


{"userId":"vincent","favTracks":{"favourite":"15","unFavourite":"121"}}

What can be the Java object for the above JSON String?


Solution

  • It really depends on how you want to map it. If you're using Jackson, for example, with the default mapping settings, your classes could look something like:

    class MyObject {
        private String userId;
        private FavTracks favTracks;
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public FavTracks getFavTracks() {
            return favTracks;
        }
    
        public void setFavTracks(FavTracks favTracks) {
            this.favTracks = favTracks;
        }
    }
    
    class FavTracks {
        private String favourite;
        private String unFavourite;
    
        public String getFavourite() {
            return favourite;
        }
    
        public void setFavourite(String favourite) {
            this.favourite = favourite;
        }
    
        public String getUnFavourite() {
            return unFavourite;
        }
    
        public void setUnFavourite(String unFavourite) {
            this.unFavourite = unFavourite;
        }
    }
    

    One remark: in your current example, the favourite and unFavourite properties are of a string type. Maybe a numeric type is more suitable?