java反序列化后不相等_java – 在Jackson中反序列化同名但不同类型的属性?

我建议你像这样使用

JsonNode:

class Event {

@JsonProperty("channel")

private JsonNode channelInternal;

private Channel channel;

private String channelStr;

/**

* Custom getter with channel parsing

* @return channel

*/

public Channel getChannel() {

if (channel == null && channelInternal != null) {

if (channelInternal.isObject()) {

int id = channelInternal.get("id").intValue();

String name = channelInternal.get("name").asText();

channel = new Channel(id, name);

}

}

return channel;

}

/**

* Custom getter with channel string parsing

* @return channel string

*/

public String getChannelStr() {

if (channelStr == null && channelInternal != null) {

if (channelInternal.isTextual()) {

channelStr = channelInternal.asText();

}

}

return channelStr;

}

}

或者像这样:

class Event {

private Channel channel;

private String channelStr;

@JsonSetter("channel")

public void setChannelInternal(JsonNode channelInternal) {

if (channelInternal != null) {

if (channelInternal.isTextual()) {

channelStr = channelInternal.asText();

} else if (channelInternal.isObject()) {

int id = channelInternal.get("id").intValue();

String name = channelInternal.get("name").asText();

channel = new Channel(id, name);

}

}

}

public Channel getChannel() {

return channel;

}

public String getChannelStr() {

return channelStr;

}

}

但我认为使用自定义解串器更常见.

这是测试代码

public static void main(String[] args) throws IOException {

ObjectMapper objectMapper = new ObjectMapper();

String source1 = "{\n" +

" \"channel\" : \"JHBHS\"\n" +

"}";

String source2 = "{\n" +

" \"channel\": {\n" +

" \"id\": 12321,\n" +

" \"name\": \"Some channel\"\n" +

" }\n" +

"}";

//Test object parsing

Event result = objectMapper.readValue(source2, Event.class);

System.out.println(String.format("%s : %s", result.getChannel().getId(), result.getChannel().getName()));

//Test string parsing

result = objectMapper.readValue(source1, Event.class);

System.out.println(result.getChannelStr());

}

并输出:

12321 : Some channel

JHBHS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值