Search code examples
javaandroidsqlitejacksonjackson-databind

Jackson object mapper not creating proper Json string from java object


I don't have A, B, C in key I have key like user_id, password etc. Also if I print toString of User class it display correct content.

Note : User object is coming form sqlite database and I double check it's working perfectly.

Please check attach User class also. I used this class to save sqlite values.

So I am getting user data from sqlite in the form of user object then converting user object into jsonstring using Jackson object mapper.

It would be great help if you point out what's wrong.

Currently I am getting below jsnstring which is wrong.

 

    {"A":1,"B":1,"C":1,"D":1,"E":1,"F":1,"G":0,"H":"ef","I":"","J":0,"K":30,"L":"","M":1,"N":0,"O":1,"P":0,"Q":"","R":"","S":1,"T":"","U":1,"V":"fkGinMCh02k:APA91bH1I8Hv1EIGdkRtZiqjvsMY-ixk_crcNxSQ3gQ1PuAOoQ0B4qllstCdOw43nZQ90JiqTpcfCyQ-_y6RsxnWcjg0gojqZ8pv4Fia_9mW4-De7nPQF4C5XIF16V5","W":"","X":0,"Y":"1","Z":"1,2,3,4,5,6,7,9,16","a":91316,"b":"email@gmail.com","c":"","d":"im","e":"F","f":"","g":1,"h":1,"i":1,"j":2478,"k":492372,"l":0,"m":10,"n":0,"o":"","p":0,"q":0,"r":0,"s":91316,"t":1,"u":1,"v":1,"w":1,"x":1,"y":0,"z":0}

Expected jsonstring

{"user_id":1,"first_name":"test","last_name":"test"}

I am getting abcd "key" in jsonstring instead of actual key while I am converting from java object.

My actual key are like user_id , email etc.

private String getUserObjectString() {
        String jsonStr = "";
        User user = here I am getting actual object content;
        ObjectMapper mapper = new ObjectMapper();
        try {
             jsonStr = mapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            Log.i("Exception","1");
            e.printStackTrace();
        }
        return jsonStr;
    }

public class User {

    public int userid;
    public String email;
    public String updatedemail;
    public String firstname;
    public String lastname;
    // Empty constructor
    public User() {

    }

    // constructor
    public User(int userid, String email, String updatedemail, String firstname, String lastname){
     this.userid = userid;
        this.email = email;
        this.updatedemail = updatedemail;
        this.firstname = firstname;
        this.lastname = lastname;
    }
    public int getID() {
        return this.userid;
    }

    public void setID(int userid) {
        this.userid = userid;
    }

    public String getemail() {
        return this.email;
    }

    public String getfirstname() {
        return this.firstname;
    }

    public String getlastname() {
        return this.lastname;
    }
    public void setFirstName(String firstname) {
        this.firstname = firstname;
    }

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

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

    public String getNewemail() {
     return this.updatedemail;
    }

    public void setNewemail(String newemail) {
     this.updatedemail = newemail;
    }

@Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", email='" + email + '\'' +
                ", updatedemail='" + updatedemail + '\'' +
                ", firstname='" + firstname + '\'' +
                ", lastname='" + lastname + '\'' +
    '}';
    }
}

This is the output of toString()

User{userid=9116, email='flutter2@gmail.com', updatedemail='', firstname='Test', lastname='Flutter2'}

Solution

  • Your User POJO should be properly annotated:

    1. All private fields should be annotated with @JsonProperty("key of your element in JSON") (for example @JsonProperty("userId") for the field private int userId;
    2. The constructor should have the annotation @JsonCreator to tell Jackson it should use that constructor when building the object
    3. All parameters passed inside the constructor should be annotated with @JsonProperty(name = "the key of your element", required = true/false)
    4. The getters should respect Java conventions getElement() - you can create them automatically with your IDE

    Once the POJO is correctly annotated, you can:

    1. Create a Java Object from a JSON string using: objectMapper.valueToTree(jsonString, User.class)
    2. Create a JSON represenation of an existing User user instance using objectMapper.writeValueAsString(user).

    Note: the annotations are not "compulsory", but highly recommended. If you don't annotate your fields and constructors / getters, Jackson will have to guess. It's never good to make a library guess, better being explicit so you can name your properties as you want or possibly be wrong without side effects.


    To sum up:

    public class User {
    
        @JsonProperty("userId") // <- note: the literal value here should be exactly what you see in your Json (case included)
        public int userid;
        @JsonProperty("email")
        public String email;
        @JsonProperty("updateEmail")
        public String updatedemail;
        @JsonProperty("firstName")
        public String firstname;
        @JsonProperty("lastName")
        public String lastname;
    
        @JsonCreator
        public User(
                @JsonProperty(name = "userId", required = true) int userid,
                @JsonProperty(name = "email", required = true) String email,
                @JsonProperty(name = "updateEmail", required = true) String updatedemail,
                @JsonProperty(name = "firstName", required = true) String firstname,
                @JsonProperty(name = "lastName", required = true) String lastname
        ) {
            this.userid = userid;
            this.email = email;
            this.updatedemail = updatedemail;
            this.firstname = firstname;
            this.lastname = lastname;
        }
    
        public int getUserid() {
            return userid;
        }
    
        public String getEmail() {
            return email;
        }
    
        public String getUpdatedemail() {
            return updatedemail;
        }
    
        public String getFirstname() {
            return firstname;
        }
    
        public String getLastname() {
            return lastname;
        }
    }