可以很容易地使用工具将java类序列化为JSON (葛森),是否有任何主流库或java语言特性提供类似的功能来将对象映射到java?
对于类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()但我不知道这个功能是否已经包含在任何主流库中。
发布于 2013-11-13 15:05:01
最后,我决定实现我自己的映射器:
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"));
}
}我的"mapper“方法需要输入对象来表示由以下模式命名的getter和setter:
(获取\set)attributeTitledName
发布于 2018-12-18 14:28:48
这是杰克逊的解决方案。Jackson主要用于将对象转换为json。
Maven
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>Java示例
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);
}
}发布于 2020-07-17 09:49:32
使用这个:
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());
}https://stackoverflow.com/questions/19955181
复制相似问题