gpt4 book ai didi

java - 如何使用 Jackson 构建不同对象的 JSON 数组?

转载 作者:搜寻专家 更新时间:2023-11-01 09:05:17 26 4
gpt4 key购买 nike

我正在构建一个 Android 应用程序,它在 CallLog 中保存有关传入/传出调用的信息。 SmsLog 中的类、传入/传出 SMS类,以及通过 DataLog 发送/接收的字节数类(class)。我让他们都实现了 JsonLog接口(interface),这样我就可以创建一个 ArrayListJsonLog s,希望它可以通过 Jackson 轻松转换为不同对象的 JSON 数组。

但是,每当我反序列化 JSON 文件时,我总是收到此错误:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance
of com.project.pojos.JsonLog, problem: abstract types either need to be mapped
to concrete types, have custom deserializer, or be instantiated with additional
type information

我该如何解决这个问题?全部JsonLog类有一个字符串属性 type ,它是 in_callout_call对于 CallLog小号,in_smsout_sms对于 SmsLog s 和 data对于 DataLog .

最佳答案

您需要在 JSON 数据中有一个类型参数或自定义反序列化器才能完成这项工作。

更简单的解决方案是前者,因为您不需要编写那么多代码,而且它可以轻松扩展,并且您可以从 JSON 数据中简单地分辨出哪个条目是什么类型。

类型信息

如果你有一个type参数:

[
{
"type": "SMS",
"id": 1,
"data": { }
},
{
"type": "CALL",
"id": 2,
"somethingOtherData": {}
}
]

然后在你的抽象JsonLog类中你可以设置类型映射信息:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(name = "SMS", value = SmsLog.class),
@Type(name = "CALL", value = CallLog.class)
})
public abstract class JsonLog {
}

反序列化器

如果您的 JSON 中不能包含此类型信息,则您需要编写自己的反序列化程序。在该反序列化器中,您需要根据实际条目确定该条目是 SmsLog 还是 CallLog

关于java - 如何使用 Jackson 构建不同对象的 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com