Bha*_*ath 5 java json jackson jackson-modules
我正在尝试使用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<CustomType> x;
}
Run Code Online (Sandbox Code Playgroud)
并使用杰克逊方法,
objectMapper.readValue(byte[] data, Class<T> type).
Run Code Online (Sandbox Code Playgroud)
因为我不确定字节数组包含什么对象,所以当它无法创建指定类型的对象时,我希望它失败.但是,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}
Run Code Online (Sandbox Code Playgroud)
这是我配置了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();
}
Run Code Online (Sandbox Code Playgroud)
objectMapper 返回一个所有字段都初始化为 null 的对象。我该如何避免这种行为?
输入对象中与目标类匹配的字段不会设置为 null。因此,请确保存在一些匹配的字段(具有相同名称的字段)。
如果您不想为 null,则可以为这些字段设置默认值。这可以完成
String s="default value";如果你的源 json 完全不同,不是单个匹配字段,那么你将得到每个字段都为空的对象。
| 归档时间: |
|
| 查看次数: |
3065 次 |
| 最近记录: |