【问题标题】:BeanUtils: Different property namesBeanUtils:不同的属性名称
【发布时间】:2016-03-31 18:31:41
【问题描述】:

我的 BeanUtils 有问题,我需要将 Map 转换为具有不同属性名称的 POJO

实体:

public class User {
    private int id;
    private String nickname;
    private int agility;

    public int getId() {
        return id;
    }

    // getters and setters
}

目标应用程序 API 返回 HashMap(通过 XML-RPC),内容如下:

user_id => "123456"
nickname => "Bob"
agility => 30

但我的 POJO 类没有 user_id 属性

如何翻译属性名称user_id => id

我没有找到该案例的任何注释

【问题讨论】:

  • Dozer 和类似的 bean 映射库是您最好的选择。此外,您发现的 JSON 映射库也可用于此目的。

标签: java apache-commons-beanutils


【解决方案1】:

BeanUtils 不适合我的情况,我使用了Gson 库。 Gson 具有功能 - 将对象转换为 json。之后,我将 json 转换为 User 类。 name 属性标注@SerializedName

实体类:

class User {
    @SerializedName("user_id")
    private int id;
    private String name;

    // getters and setters here
    // .toString
}

用法:

Map<String,String> apiObject = new HashMap<>();

apiObject.put("user_id","123123");
apiObject.put("name","Bob");

Gson gson = new Gson();
String json = gson.toJson(values);
User user = gson.fromJson(json, User.class);

System.out.println(user);

示例输出:

User{id=123123, name='Bob'}

【讨论】:

    【解决方案2】:

    如果在你收到HashMap之后允许以后再修改,你就改改key。

    map.put("id", map.remove("user_id"));
    

    然后使用 BeanUtils 填充您的 bean:

    User usr = new User();
    BeanUtils.populate(usr, map);
    

    【讨论】:

    • 你可以在一个map中的20个字段,用它来替换你的data map的key。
    • 这个方案需要支持fields-replace list,不灵活。 n+1 个实体和 20 多个字段 -> 支持地狱。我想到了 gson 的把戏(我稍后会检查并写下)
    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多