【问题标题】:JsonIgnoreProperties not workingJsonIgnoreProperties 不起作用
【发布时间】:2014-01-08 04:22:03
【问题描述】:

我有以下简单的类:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties({ "thirdField" })
public class Message {

    private TypeA type;
    private String producer;

//Getters and Setters

}

在我的测试课中

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
   public void testMethd() {
   ObjectMapper objectMapper = new ObjectMapper();
   objectMapper.configure(MapperFeature.USE_ANNOTATIONS, true);
   Class<T> instanceType = Message.class;

   String msgBody = "{\"producer\": \"clientApp\", \"type\": \"aType\", \"thirdField\": []}";
   objectMapper.readValue(msgBody, instanceType);
   }
}

我要做的就是将上面的 json 字符串转换为 Message 类并忽略“thirdField”。但我不断得到

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "thirdField" (class Message), not marked as ignorable (2 known properties: , "type", "producer"])

【问题讨论】:

    标签: jackson


    【解决方案1】:

    您混合了不同版本的杰克逊。 请注意,您从 org.codehaus.jackson.annotate(版本 1.x)导入 JsonIgnoreProperties 当您使用来自 com.fasterxml.jackson.databind(版本 2.x)的 ObjectMapper 时。

    【讨论】:

    • 好收获。我将其更改为 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;但仍然得到相同的异常
    • @kk1957 我复制了您的案例,唯一的区别是我从 com.fasterxml.jackson.annotation 导入了 JsonIgnoreProperties 并且它有效 - 没有例外,消息对象被正确反序列化。尝试检查 github.com/LukaszWiktor/json-ignore-properties-test 并运行 Test.main()
    • 谢谢,我在查看github.com/helun/Ektorp 的示例在使用最新版本的 jackson lib 时到底做错了什么。
    • @MihaPirnat 很高兴我的回答在 3 年后仍然有用。
    • @gaurav 令人惊讶的是,我的回答在 6 年后仍然有用!
    【解决方案2】:

    尝试使用最新的 Jackson 版本 (2.4):

    import com.fasterxml.jackson.annotation.JsonIgnoreProperties
    @JsonIgnoreProperties({"id"})
    

    您可以在此处找到使用 2.4 版实现的示例: http://www.ibm.com/developerworks/java/library/j-hangman-app/index.html

    【讨论】:

      【解决方案3】:

      上面的任何答案都对我不起作用,我找到了一种解决方法,我重新初始化了对象和值(复制了对象)。

      【讨论】:

        【解决方案4】:

        我找到了解决方案。 尝试添加

        @JsonSerialize(include= JsonSerialize.Inclusion.NON_EMPTY)
        

        关于你的班级

        @JsonSerialize(include= JsonSerialize.Inclusion.NON_EMPTY)
        class ResponseModel {
         //your properties here
         @JsonIgnoreProperties("messageList","contactList","sender")
            var contactList= ArrayList<ContactModel>()
        }
        

        这会解决你的问题,伙计。

        【讨论】:

          猜你喜欢
          • 2017-04-28
          • 2018-10-18
          • 1970-01-01
          • 1970-01-01
          • 2021-09-18
          • 1970-01-01
          • 2019-11-19
          • 1970-01-01
          • 2021-07-24
          相关资源
          最近更新 更多