首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象属性映射到Java的最简单方法

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

Stack Overflow用户
提问于 2013-11-13 13:31:54
回答 3查看 9.7K关注 0票数 1

可以很容易地使用工具将java类序列化为JSON (葛森),是否有任何主流库或java语言特性提供类似的功能来将对象映射到java?

对于类C1来说,这是一种自然的方法:

代码语言:javascript
复制
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:

代码语言:javascript
复制
C1 o1 = ...

..。可以是:

代码语言:javascript
复制
Map<String, Integer> result = new HashMap<>();
result.put("x",o1.getX());
result.put("y",o1.getY());

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

代码语言:javascript
复制
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);

我知道我可以自己开发这个工具,比如:

代码语言:javascript
复制
Class.getDeclaredFields()

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-11-13 15:05:01

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

代码语言:javascript
复制
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;
    }
}

一个愚蠢的例子:

代码语言:javascript
复制
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"));
    }
}

我的"mapper“方法需要输入对象来表示由以下模式命名的getter和setter:

(获取\set)attributeTitledName

票数 5
EN

Stack Overflow用户

发布于 2018-12-18 14:28:48

这是杰克逊的解决方案。Jackson主要用于将对象转换为json。

Maven

代码语言:javascript
复制
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>

Java示例

代码语言:javascript
复制
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; }

    public void main(String[] args) {
            C1 obj = new C1();
            obj.setX(10);
            obj.setY(20);

            Map<String, Object> map = new ObjectMapper().convertValue(obj, Map.class);
            System.out.println(map); 
    }

}
票数 3
EN

Stack Overflow用户

发布于 2020-07-17 09:49:32

使用这个:

代码语言:javascript
复制
File  file = new File();
PropertyDescriptor[] fileObjectDescriptors = 
                         PropertyUtils.getPropertyDescriptors(file);
List<PropertyDescriptor> filePropertyList = 
                      Arrays.asList(fileObjectDescriptors);
for(PropertyDescriptor fileProperty:filePropertyList){
    attribute = fileProperty.getName()
    value = PropertyUtils.getProperty(file, fileProperty.getName());
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19955181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档