AI编程助手
AI免费问答

使用可变键定义 POJO

王林   2024-02-09 08:42   647浏览 转载

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;
}</string></string>

最后为了适应variablekeys,我定义了一个新对象,如下所示:

class city {

map<string citydata> city;

}</string>

但是,我收到以下错误:

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Berlin" , not marked as ignorable (0 known properties: ])

如何将变量键存储在 pojo 中?这是必不可少的东西,所以我想通过 jackson objectmapper readvalue 检索它。

解决方法

您需要将数据解析为 map<string></string>,而不是解析为包含 map 属性的对象。您的根级别是地图。

map<string citydata> parsed = objectmapper.readvalue(
  input,
  new typereference<map citydata>>() {});</map></string>

使用您的类型 city,您可以使用以下结构解析 json:

{
  "city": {
    "Berlin": { ... },
    "Paris": { ... }
  }
}

其中将您的实际 json 嵌套在键“city”下(map<string> city</string>)。

声明:本文转载于:stackoverflow,如有侵犯,请联系admin@php.cn删除