java反射實現物件轉json字串
阿新 • • 發佈:2021-01-12
java反射實現物件轉json字串
這裡只作為反射學習的一個案例,當然有好多json工具可以實現json字串和物件的轉換。
定義倆個函式,一個是不包含物件的物件裝json字串,一個是包含物件的物件轉json字串,主要思路就是利用反射來獲取物件的屬性名和屬性值,然後拼接成json字串
import java.lang.reflect.Field;
//java物件轉json物件字串
public class test {
//所有屬性為基本型別或String
public static String transformString(Object object) throws Exception {
String res="{";
Class<?> c=object.getClass();
Field[] fields=c.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
res+=('"'+field.getName()+'"'+":"+'"'+field.get(object).toString()+'"');
if(field!= fields[fields.length-1]) {
res+=",";
}
}
res+="}";
return res;
}
//包含物件的json
public static String newTransformString(Object object) throws Exception {
String res="{";
Class<?> c=object.getClass();
Field[] fields=c.getDeclaredFields();
for ( Field field : fields) {
field.setAccessible(true);
res+=('"'+field.getName()+'"'+":");
if(field.getType().isPrimitive()||field.get(object) instanceof String){
res+=('"'+field.get(object).toString()+'"');
}else {
res+=newTransformString(field.get(object));
}
if(field!=fields[fields.length-1]) {
res+=",";
}
}
res+="}";
return res;
}
public static void main(String[] args) throws Exception {
Student student=new Student();
student.setSno(10001);
student.setName("張三");
student.setMajor("軟體工程");
String jsonString=transformString(student);
System.out.println(jsonString);
Person person=new Person();
person.setName("John Doe");
person.setAge(18);
person.setAddress(new Address("china",10000));
String newJsonString=newTransformString(person);
System.out.println(newJsonString);
}
}