將物件解析為JSON資料和將JSON資料解析為物件的簡單例項

disable發表於2021-09-09

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);

}

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();

}

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;

}

}

原文連結:http://www.apkbus.com/blog-813041-61013.html

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/200/viewspace-2815079/,如需轉載,請註明出處,否則將追究法律責任。

相關文章