如何使用反射来获取POJO的属性名称和值? [英] How can use reflection to get the property names and values from a POJO?
问题描述
List< T>
对象并转换为JSON。 希望这会有道理
/ **
*
*不完整!!!明显!!!
* /
public abstract class Jsonator< T>实现Serializable {
private Class< T> entityClass;
private JSONObject json;
private JSONArray jsonArray;
public Jsonator(Class< T> entityClass){
this.entityClass = entityClass;
$ b $ public void convert(List< T> 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);
$ b catch(Exception ex){
}
}
public String error(){
returnERROR ;
public String results(){
if(json!= null){
return json.toJSONString();
}
return[];
当我到达 Object obj
部分,我的 obj
是正确的。我可以调试它并查看类的名称和值。
让我们说这个类是这样的:
public class User {
private firstName;
私人姓氏;
... getters .... setters .... etc ...
}
现在, obj
是一个网站。
好的,然后我尝试获取字段名(firstName,lastName),但字段对象为空。
我做错了什么?
谢谢
编辑
我得到它的工作!这不是完成的代码,但它现在正在做我想要的。
我读过谷歌和杰克逊也会这样做。如果有人能提供一个关于如何从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;
$ b $ / **
*
* @author Cecil.Meeks
* /
public abstract class Jsonator< T>实现Serializable {
private Class< T> entityClass;
private JSONObject json;
private JSONArray jsonArray;
public Jsonator(Class< T> entityClass){
this.entityClass = entityClass;
$ b $ public void convert(List< T> 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);
$ b catch(SecurityException ex){
ex.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
public String error(){
returnERROR;
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实现Serializable {
private String siteKey;
私人字符串网站;
private String siteType;
私人字符串地址1;
私人字符串地址2;
私人字符串城市;
私人字符串zipCode;
私人字符串createdBy;
private String glCode;
$ b $ 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;
$ b @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;
$ b @Column(name =City,unique = false,length = 125,nullable = true)
public String getCity(){
return city ;
}
public void setCity(String city){
this.city = city;
$ b @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扩展了Jsonator< Site> {
public SiteJsonator(){
super(Site.class);
}
}
@Controller
@RequestMapping(value =/ sites)
公共类SitesController {
@Autowired
私人SiteService siteService;
@RequestMapping(value =/,method = RequestMethod.GET,headers =Accept = application / json)
@ResponseBody
public String index(ModelMap map) {
SiteJsonator list = new SiteJsonator();;
尝试{
list.convert(siteService.getAll());
return list.results();
}
catch(Exception ex){
return list.error();
}
}
}
更新2
对于感兴趣的人来说,以下是更好的 Jsonator
:
https://gist.github.com/3893242
您可以传入排除字符串[],但不包含这些字符串。此外,它还有一个标准的结果,消息等,我们喜欢在我们的AJAX请求中传回。好的ExtJS。
您需要使用 使用 So I'm writing an "POJO to JSON" converter. I want to be able to pass in a Hopefully this will make sense When I get to the Let's say that class is this: So that now, What am I doing wrong? Thanks EDIT I got it to work! This is not finished code, but it's doing exactly what I want for now.
I've read that Google and Jackson will do this too. If someone can provide a good link on how to selectively pick properties from a POJO, then I'm all ears. Or better yet, I'd like to know WHY I shouldn't be doing this, this way? Thanks! Jsonator (NOT FINISHED) Site Class EXAMPLE UPDATE 2 Here is the better https://gist.github.com/3893242 You can pass in an "exclude" String[] and it will not include those. Plus, it has a standard "results, message, etc" that we like to pass back in our AJAX requests. Good for ExtJS. You need to use With 这篇关于如何使用反射来获取POJO的属性名称和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! #getDeclaredFields()
包含专用字段 #getFields()
只列出公共的。
私人
字段时,您还会遇到访问限制问题,因此您可能需要查看 域#setAccessible()
方法。List<T>
object and convert to JSON./**
*
* NOT COMPLETE!!! OBVIOUSLY!!!
*/
public abstract class Jsonator<T> implements Serializable {
private Class<T> entityClass;
private JSONObject json;
private JSONArray jsonArray;
public Jsonator(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void convert(List<T> 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
section, my obj
is correct. I can debug it and see the name and value of the class. public class User {
private firstName;
private lastName;
... getters....setters....etc...
}
obj
is a Site.
OK, I then try to get the field names (firstName, lastName) but the fields object is empty.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<T> implements Serializable {
private Class<T> entityClass;
private JSONObject json;
private JSONArray jsonArray;
public Jsonator(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void convert(List<T> 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<Site> {
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();
}
}
}
Jsonator
for those interested:#getDeclaredFields()
to include private fields, #getFields()
only lists the public ones. private
fields you will also run into access restriction problems, so you probably want to look into the Field#setAccessible()
method as well.