如何使用reflection从POJO获取属性名称和值?

所以我正在写一个“POJO to JSON”转换器。 我希望能够传入List对象并转换为JSON。

希望这是有道理的

 /** * * NOT COMPLETE!!! OBVIOUSLY!!! */ public abstract class Jsonator implements Serializable { private Class entityClass; private JSONObject json; private JSONArray jsonArray; public Jsonator(Class entityClass) { this.entityClass = entityClass; } public void convert(List paObjectList) throws IllegalArgumentException, IllegalAccessException { json = new JSONObject(); jsonArray = new JSONArray(); try { for (Object obj : paObjectList) { JSONObject objJson = new JSONObject(); Class kls = obj.getClass(); Field[] fields = kls.getFields(); for (Field field : fields) { objJson.put(field.getName(), (T) field.get(obj)); } jsonArray.add(objJson); } json.put("results", jsonArray); } catch (Exception ex) { } } public String error() { return "ERROR"; } public String results() { if (json != null) { return json.toJSONString(); } return "[]"; } } 

当我到达Object obj部分时,我的obj是正确的。 我可以调试它,看看类的名称和值。

让我们说这个课是这样的:

 public class User { private firstName; private lastName; ... getters....setters....etc... } 

所以现在, obj是一个网站。 好的,然后我尝试获取字段名称(firstName,lastName),但fields对象为空。

我究竟做错了什么?

谢谢

编辑

我得到了它的工作! 这不是完成的代码,但它正在完成我现在想要的。 我读过谷歌和jackson也会这样做。 如果有人可以提供一个关于如何从POJO中有选择地选择属性的良好链接,那么我全都耳朵。

或者更好的是,我想知道为什么我不应该这样做,这样呢?

谢谢!

Jsonator(未完成)

 import java.io.Serializable; import java.lang.reflect.Field; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author Cecil.Meeks */ public abstract class Jsonator implements Serializable { private Class entityClass; private JSONObject json; private JSONArray jsonArray; public Jsonator(Class entityClass) { this.entityClass = entityClass; } public void convert(List paObjectList) throws IllegalArgumentException, IllegalAccessException { json = new JSONObject(); jsonArray = new JSONArray(); try { for (Object obj : paObjectList) { JSONObject objJson = new JSONObject(); Class kls = obj.getClass(); Field[] fields = kls.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); objJson.put(field.getName(), field.get(obj)); } jsonArray.add(objJson); } json.put("results", jsonArray); } catch (SecurityException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } public String error() { return "ERROR"; } public String results() { if (json != null) { return json.toJSONString(); } return "[]"; } } 

网站类

 import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "Sites") public class Site implements Serializable { private String siteKey; private String site; private String siteType; private String address1; private String address2; private String city; private String zipCode; private String createdBy; private String glCode; public Site() { } @Id @GenericGenerator(name = "generator", strategy = "guid", parameters = {}) @GeneratedValue(generator = "generator") public String getSiteKey() { return siteKey; } public void setSiteKey(String siteKey) { this.siteKey = siteKey; } @Column(name = "Site", unique = true, length = 125, nullable = false) public String getSite() { return site; } public void setSite(String site) { this.site = site; } @Column(name = "SiteType", unique = false, length = 8, nullable = true) public String getSiteType() { return siteType; } public void setSiteType(String siteType) { this.siteType = siteType; } @Column(name = "Address1", unique = false, length = 125, nullable = true) public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } @Column(name = "Address2", unique = false, length = 125, nullable = true) public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } @Column(name = "City", unique = false, length = 125, nullable = true) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name = "ZipCode", unique = false, length = 50, nullable = true) public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } @Column(name = "CreatedBy", unique = false, length = 125, nullable = true) public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Column(name = "GLCode", unique = false, length = 11, nullable = true) public String getGlCode() { return glCode; } public void setGlCode(String glCode) { this.glCode = glCode; } } 

 public class SiteJsonator extends Jsonator { public SiteJsonator() { super(Site.class); } } @Controller @RequestMapping(value = "/sites") public class SitesController { @Autowired private SiteService siteService; @RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json") @ResponseBody public String index(ModelMap map) { SiteJsonator list = new SiteJsonator();; try { list.convert(siteService.getAll()); return list.results(); } catch (Exception ex) { return list.error(); } } } 

更新2

对于那些感兴趣的人Jsonator ,这是更好的Jsonator

https://gist.github.com/3893242

您可以传入“exclude”String [],但不包括那些。 此外,它还有一个标准的“结果,消息等”,我们希望在我们的AJAX请求中传回。 对ExtJS有好处。

您需要使用#getDeclaredFields()来包含私有字段, #getFields()仅列出公共字段。

对于private字段,您也会遇到访问限制问题,因此您可能也希望查看Field#setAccessible()方法。

您可能需要使用kls.getDeclaredFields()而不是kls.getfields。 如果杰森的对象是您的关注,我建议您使用jackson科德豪斯图书馆。 您可以从POJO中获取或设置JsonString … HTH