java - 将对象属性映射到 Java 映射的最简单方法

标签 java dictionary

有一些易于使用的工具可以将java类序列化为JSON字符串(gson),是否有主流库或java语言功能提供类似的功能将对象映射到java map 中?

对 C1 类执行此操作的自然方法:

class C1
{
  private int x;
  private int y;

  public int getX() { return x; }
  public void setX(int x) { this.x = x; }

  public int getY() { return y; }
  public void setY(int y) { this.y = y; }
}

和对象o1:

C1 o1 = ...

...可能是:

Map<String, Integer> result = new HashMap<>();
result.put("x",o1.getX());
result.put("y",o1.getY());

gson 的工作方式非常简单(来自 gson 网站):

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);

我知道我可以使用以下内容自行开发该工具:

Class.getDeclaredFields()

但我想知道这个功能是否已经包含在任何主流库中。

最佳答案

最后,我决定实现自己的映射器:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class Serializer {
    static public Map<String, Object> object2Map(Object o)
    {
        Class co = o.getClass();
        Field [] cfields = co.getDeclaredFields();
        Map<String, Object> ret = new HashMap<>();
        for(Field f: cfields)
        {
            String attributeName = f.getName();
            String getterMethodName = "get"
                               + attributeName.substring(0, 1).toUpperCase()
                               + attributeName.substring(1, attributeName.length());
            Method m = null;
            try {
                m = co.getMethod(getterMethodName);
                Object valObject = m.invoke(o);
                ret.put(attributeName, valObject);
            } catch (Exception e) {
                continue; 
            }
        }
        return ret;
    }
}

一个愚蠢的使用示例:

public class JavaUtilsTests {

    static public class C1
    {

        public C1(int x, int y) {
            this.x = x;
            this.y = y;
        }       

        public int getX() { return x; }
        public void setX(int x) { this.x = x; }

        public int getY() { return y; }
        public void setY(int y) { this.y = y; }

        private int x;
        private int y;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        C1 o1 = new C1(1,2);
        Map<String, Object> attributesMap = Serializer.object2Map(o1);
        System.out.printf("x=%s\ty=%s\n", attributesMap.get("x"), attributesMap.get("y"));
    }
}

我的“映射器”方法需要输入对象来呈现按以下模式命名的 getter 和 setter:

(获取|设置)attributeTitledName

关于java - 将对象属性映射到 Java 映射的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19955181/

相关文章:

c# - 复制字典没有给我预期的结果

c# - 添加到字典中的字典

java - 使用反射获取Java数组中的字段 "length"

java - 使用 JSF primefaces 和 Google App Engine 数据存储的 CRUD 最佳实现是什么

java - 为什么对象到 byte[] 在 java 中返回困惑的字符?

python - 如何识别字典中的匹配值并仅使用这些键创建一个新字符串?

c# - JSON 基于字典键推断类类型

unit-testing - 无法让 NUnit 的 Assert.Throws 正常工作

使用 compuateifpresent 的 java 计算 HashMap 不起作用

java - 输入 stream.read 返回 0 或 -1?