杰克逊对象映射器无法从Java对象创建正确的JSON字符串。

huangapple go评论143阅读模式
英文:

Jackson object mapper not creating proper Json string from java object

问题

以下是翻译好的内容:

我在关键字中没有A、B、C,我有像user_id、password等这样的关键字。另外,如果我打印User类的toString,它会显示正确的内容。

注意:User对象来自SQLite数据库,我已经仔细检查过它的工作情况。

请检查附加的User类。我使用这个类来保存SQLite的值。

因此,我正在以用户对象的形式从SQLite获取用户数据,然后使用Jackson对象映射器将用户对象转换为json字符串。

如果您能指出问题所在,将会非常有帮助。

目前我得到的错误json字符串如下:

{"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}

期望的json字符串如下:

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

当我从Java对象转换时,我得到的是abcd "key"而不是实际的关键字。

这是我的getUserObjectString()方法:

private String getUserObjectString() {
    String jsonStr = "";
    User user = 这里我得到实际的对象内容;
    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonStr = mapper.writeValueAsString(user);
    } catch (JsonProcessingException e) {
        Log.i("Exception","1");
        e.printStackTrace();
    }
    return jsonStr;
}

User类如下:

public class User {

    public int userid;
    public String email;
    public String updatedemail;
    public String firstname;
    public String lastname;

    // 空构造函数
    public User() {

    }

    // 带参数的构造函数
    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 + '\'' +
                '}';
    }
}

toString()方法的输出如下:

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

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'}

答案1

得分: 2

你的 User POJO 应该被正确地注解:

  1. 所有私有字段应该使用 @JsonProperty("JSON中的元素键") 进行注解(例如,对于字段 private int userId,应该使用 @JsonProperty("userId"));
  2. 构造函数应该有 @JsonCreator 注解,以告诉 Jackson 在构建对象时应该使用该构造函数;
  3. 构造函数中传递的所有参数应该使用 @JsonProperty(name = "元素的键", required = true/false) 进行注解;
  4. Getter 方法应该遵循 Java 的约定,例如 getElement(),你可以在你的集成开发环境中自动生成它们。

一旦正确注解了 POJO,你可以:

  1. 使用以下方式从 JSON 字符串创建一个 Java 对象:objectMapper.valueToTree(jsonString, User.class)
  2. 使用 objectMapper.writeValueAsString(user) 来创建一个现有 User user 实例的 JSON 表示。

注意:这些注解并不是“强制性的”,但强烈建议使用。如果不为字段、构造函数和获取器方法进行注解,Jackson 将不得不猜测。最好明确注明,这样你可以按照自己的意愿命名属性,或者可能出现错误而没有副作用。

总结一下:

public class User {

    @JsonProperty("userId") // <- 注意:这里的文字值应该与你的 JSON 中的键一模一样(包括大小写)
    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;
    }
}
英文:

Your User POJO should be properly annotated:

  1. All private fields should be annotated with @JsonProperty(&quot;key of your element in JSON&quot;) (for example @JsonProperty(&quot;userId&quot;) 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 = &quot;the key of your element&quot;, 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(&quot;userId&quot;) // &lt;- note: the literal value here should be exactly what you see in your Json (case included)
public int userid;
@JsonProperty(&quot;email&quot;)
public String email;
@JsonProperty(&quot;updateEmail&quot;)
public String updatedemail;
@JsonProperty(&quot;firstName&quot;)
public String firstname;
@JsonProperty(&quot;lastName&quot;)
public String lastname;
@JsonCreator
public User(
@JsonProperty(name = &quot;userId&quot;, required = true) int userid,
@JsonProperty(name = &quot;email&quot;, required = true) String email,
@JsonProperty(name = &quot;updateEmail&quot;, required = true) String updatedemail,
@JsonProperty(name = &quot;firstName&quot;, required = true) String firstname,
@JsonProperty(name = &quot;lastName&quot;, 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;
}
}

huangapple
  • 本文由 发表于 2020年7月25日 19:17:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63087675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定