在Jackson中反序列化具有相同名称但不同类型的属性?

我有一个REST API,它返回JSON响应为:

{

"channel" : "JHBHS"

}

有时它返回:

{

"channel": {

"id": 12321,

"name": "Some channel"

}

}

我有一个像这样的POJO:

public class Event {

private String channel;

@JsonProperty("channel")

private Channel channelObj;

}

public class Channel {

private int id;

private String name;

}

那么,有没有一种方法(不是写你自己的其他

中)Jackson2,这将有助于我映射channel在JSON来String时,它的A型StringChannel类型时,它是一个JSON对象?

或者换句话说,在Jackson中,有没有一种方法可以按type变量而不是by 映射name

回答:

我可以建议您像这样使用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

以上是 在Jackson中反序列化具有相同名称但不同类型的属性? 的全部内容, 来源链接: utcz.com/qa/420943.html

回到顶部