php小编子墨在这篇文章中将为大家介绍如何使用可变键定义pojo(普通旧式的java对象)。在编程中,pojo是指一个简单的java对象,它不依赖于任何特定的框架或库。可变键是指在定义pojo时,键(属性名)可以根据需要进行动态的修改或扩展。这种技术让我们能够更灵活地操作对象属性,提高代码的可读性和可维护性。接下来,我们将深入探讨如何使用可变键定义pojo,并给出一些实际应用场景的示例。
我正在尝试将 json 转换为 pojo,其中键是可变的。例如:以下示例中的柏林、巴黎:
{
"berlin": {
"en-us": {
"displayname": "us",
"supportedlanguage": [
"us"
],
"fullexample": "hello us"
},
"en-ca": {
"displayname": "ca",
"supportedlanguage": [
"ca"
],
"fullexample": "hello ca"
}
},
"paris": {
"en-us": {
"displayname": "us",
"supportedlanguage": [
"us"
],
"fullexample": "hello us"
},
"en-ca": {
"displayname": "ca",
"supportedlanguage": [
"ca"
],
"fullexample": "hello ca"
}
}
}对于变量键(柏林、巴黎)内的所有内容,例如:
"en-us": {
"displayname": "us",
"supportedlanguage": [
"us"
],
"fullexample": "hello us"
},
"en-ca": {
"displayname": "ca",
"supportedlanguage": [
"ca"
],
"fullexample": "hello ca"
}我定义的类如下:
class citydata {
map <string, languagedata> locale;
}
class languagedata {
string displayname;
list<string> supportedlanguage;
string fullexample;
}最后为了适应variablekeys,我定义了一个新对象,如下所示:
class city {
map<string, citydata> city;
}但是,我收到以下错误:
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Berlin" , not marked as ignorable (0 known properties: ])
如何将变量键存储在 pojo 中?这是必不可少的东西,所以我想通过 jackson objectmapper readvalue 检索它。
您需要将数据解析为 map<string、citydata>,而不是解析为包含 map 属性的对象。您的根级别是地图。
map<string, citydata> parsed = objectmapper.readvalue(
input,
new typereference<map<string, citydata>>() {});使用您的类型 city,您可以使用以下结构解析 json:
{
"city": {
"Berlin": { ... },
"Paris": { ... }
}
}其中将您的实际 json 嵌套在键“city”下(map<string、citydata> city)。
以上就是使用可变键定义 POJO的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号