实体属性序列化两次 [英] Entity properties serialized twice

查看:67
本文介绍了实体属性序列化两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring 3.3中,我有一个映射到数据库表的实体.在这个实体类中,我具有用@JsonProperty注释的所有属性,例如@JsonProperty("ID").进入控制器,将通过使用DAO/存储库调用服务以获取此类实体.这很好用,但是当我使用@ResponseBody将这个实体发送回请求者时,所有属性都会发送两次.按要求一次,但又一次从小写开始直到出现第一个骆驼大写字母.一个例子...

In Spring 3.3 I have an entity which is mapped to a database table. In this entity class I have all properies annotated with @JsonProperty, for instance @JsonProperty("ID"). Stepping into the controller a service is called to get such an entity by using a DAO/repository. This works well but when I send this entity back to the requestor using @ResponseBody all properties are sent twice. Once as demanded but one more time beginning lowercase until the first camel case letter occurs. An example...

public class MyEntity {
    @JsonProperty("MYSpecialSuperId")
    private String MYSpecialSuperId;

    ...

    public String getMYSpecialSsuperId() {
        return this.MYSpecialSuperId;
    }

}

在JSON字符串化之后,结果是:

After JSON stringifying the result is:

{ "MYSpecialSuperId":""9", "myspecialSuperId":"9" }

为什么该属性在结果中出现两次,为什么字母不同???

Why is the property twice in the result and why is the lettering different???

顺便说一句:我的想法不是让Java属性以大写字母开头,甚至不止一个大写字母.

BTW: It was not my idea to let Java properties begin with an uppercase letter even yet with more than one uppercase letter.

推荐答案

Jackson的 ObjectMapper 使用Java bean模式.换句话说,它期望以下内容

Jackson's ObjectMapper uses the Java bean pattern. In other words, it expects the following

public class Foo {
    public Object bar;

    public Object getBar() {...}

    public void setBar(Object bar) {...}
}

getter和setter分别以 get set 开头,后跟相应的字段名称,首字母大写.如果您将代码更改为

The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized. If you change your code to

public class MyEntity {
    @JsonProperty("MYSpecialSuperId")
    private String mySpecialSuperId;

    ...

    public String getMySpecialSuperId() {
        return this.mySpecialSuperId;
    }

}

请注意,该字段以小写的 my 开头,而不是大写的(不管 @JsonProperty 值如何),我在其中删除了多余的 s getMYSpecialSsuperId 并使用小写的 y .因此,现在字段名称与getter名称匹配,并且jackson知道该属性是相同的,不需要序列化两次.

Note that the field starts with lowercase my instead of uppercase (regardless of the @JsonProperty value), I removed the extra s in getMYSpecialSsuperId and used a lowercase y. So now the field name matches the getter name and jackson knows that the property is the same and doesn't need to serialize twice.

如果您别无选择,可以遵循 Katona发表在评论中的内容并使用

If you have no choice, you can follow what Katona posted in the comments and use

@JsonAutoDetect(getterVisibility=Visibility.NONE)

使杰克逊完全忽略吸气剂,仅使用这些字段来序列化您的JSON.

to make jackson ignore the getters completely and only use the fields to serialize your JSON.

这篇关于实体属性序列化两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆