【问题标题】:Convert a pojo variable to another bean which takes it as list of name and value将 pojo 变量转换为另一个将其作为名称和值列表的 bean
【发布时间】:2017-12-19 22:52:29
【问题描述】:

我有一个带有一组变量的 bean。我想将它们转换为另一个只有名称和值的 bean 说参数。我需要列出名称-值对中所有变量的参数列表。

我正在考虑 Dozer 或 mapstruct,但这似乎并没有真正的帮助。

今天,使用objectmapper将其转换为地图,迭代地图并创建参数列表。

任何帮助将不胜感激。

【问题讨论】:

  • 是否要将变量从一个 bean 复制到另一个?
  • 如果你提供一个小例子来说明你的 bean 的样子,我可以为 MapStruct 提供更多帮助
  • 是的,阿比吉特。我需要转换
  • 我建议您使用示例更新您的问题。此外,您尝试做的事情在 Java 中实际上是不可能的。据我了解Parameter 中的name 实际上是TestClass 中的字段名称。为此,您需要使用反射,并且它仅适用于 Java 8 和 -parameters 选项。

标签: spring spring-boot mapping dozer mapstruct


【解决方案1】:
    class TestClass{
    private String str1;
    private String str2;
    private String str3;
    }

    Class Paramters{
    private String name;
    private String value;
    }

    **Bean1:**
    '[
        {
            "str1": "string",
            "str2": "string",
            "str3": "string"
        },
        {
            "str1": "string1",
            "str2": "string1",
            "str3": "string1"
        }
    ]'

    To Convert **Bean2**

   '[{
        "parameters": [
            {
                "name": "str1",
                "value": "string"
            },
            {
                "name": "str2",
                "value": "string"
            },
            {
                "name": "str3",
                "value": "string"
            }
        ]
    },
    {
        "parameters": [
            {
                "name": "str1",
                "value": "string"
            },
            {
                "name": "str2",
                "value": "string"
            },
            {
                "name": "str3",
                "value": "string"
            }
        ]}]'

【讨论】:

  • @Filip 希望上面的例子可以帮助你为我得出答案。
【解决方案2】:

Mapstruct 等通常从一个 bean 转换为另一个,您实际上是在尝试转换为 map 并将其包装为 bean。 像BeanMap 这样的东西会更合适。

未经测试的示例代码:

class Bean2 {
    private final Map<String, Object> properties;

    public Bean2(Map properties) { this.properties = properties }


    public static class Entry { String name, String value /* getters and setters */}

    @JsonProperty
    public List<Map<String, Object>> getProperties() {
        // build a map of maps here, each map would have 
    } 
} 

那么就:

new Bean2(new BeanMap(bean2))

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多