1.实例类Student.java
package demo06;
public class Student {
private String name;
private int age;
private String gender;
public Student(){}
public Student(String name, int age, String gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", gender=" + gender
+ "]";
}
}
2.测试类及实现类
package demo06;
import java.lang.reflect.Field;
import org.json.JSONObject;
public class Test01 {
public static void main(String[] args) {
Student stu=new Student("zm",23,"男");
String json=toJSON(stu);
System.out.println(json);
Student st=getObject1(json,Student.class);
System.out.println(st);
}
/**
* 将对象解析为json数据
* @param obj
* @return String
*/
public static String toJSON(Object obj){
JSONObject json=new JSONObject();
Class<?>cla=obj.getClass();
Field field[]=cla.getDeclaredFields();
for (Field f : field) {
String name=f.getName();
f.setAccessible(true);
try {
Object val=f.get(obj);
json.put(name, val);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return json.toString();
}
/**
* 将JSON数据解析为对象
* @param json
* @param t
* @return
*/
public static <T>T getObject1(String json,Class<T> t){
T t1=null;
try {
t1=t.newInstance();//获取实例时一定要加上默认的构造方法(**)
Field field[]=t.getDeclaredFields();
JSONObject js=new JSONObject(json);
for (Field f : field) {
String name=f.getName();
Object val=js.get(name);
f.setAccessible(true);
f.set(t1, val);
}
} catch (Exception e) {
e.printStackTrace();
}
return t1;
}
}