加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Jackson Object Mapper readvalue以字节为单位返回一

发布时间:2020-12-15 01:06:48 所属栏目:Java 来源:网络整理
导读:我正在尝试使用jackson对象映射器将字节数组反序列化为java类型. @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class A { String s; String b; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonInc

我正在尝试使用jackson对象映射器将字节数组反序列化为java类型.

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class A {
     String s;
     String b;
    }

   @JsonIgnoreProperties(ignoreUnknown = true)
   @JsonInclude(JsonInclude.Include.NON_NULL)   
   public class B {
     String c;
     String b;
   }

      @JsonIgnoreProperties(ignoreUnknown = true)
       @JsonInclude(JsonInclude.Include.NON_NULL)   
       public class C {
         List

并使用杰克逊方法,

objectMapper.readValue(byte[] data,Class

因为我不确定字节数组包含什么对象,所以当它无法创建指定类型的对象时,我希望它失败.但是,objectMapper返回一个对象,其所有字段都初始化为null.我该如何避免这种行为?

Ex: 
byte[] b; //contains Class B data
byte[] a; //contains Class A data
byte[] c// contains Class C data
A a = objectMapper.readValue(c,A.class) is returning 
{s=null,b = null}

这是我配置了ObjectMapper,

@Bean
    public ObjectMapper objectMapper(HandlerInstantiator handlerInstantiator) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.handlerInstantiator(handlerInstantiator);
        builder.failOnEmptyBeans(false);
        builder.failOnUnknownProperties(false);
        builder.simpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        builder.timeZone("UTC");
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);

        return builder.build();
    }
最佳答案

objectMapper returns an object with all fields initialized to null. How
do i avoid this behavior?

输入对象中与目标类匹配的字段不会设置为null.
因此,请确保存在一些匹配的字段(具有相同名称的字段).

如果您不想要null,则可能具有这些字段的默认值.
这可以做到

> at field declaration String s =“default value”;
>默认情况下,无参数构造函数. Jackson将调用此构造函数,然后为JSON数据中的匹配字段设置值.

如果您的源json完全不同,而不是单个匹配字段,那么您将获得每个字段为空的对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读