package com.vzone.tmdsdk.tool;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.Collection;
/**
* Created by 詹子聪 on 2016/6/14.
*/
public class JsonTool {
public static String objToJson(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
JSONObject jsonObject = new JSONObject();
for (Field field : fields) {
try {
field.setAccessible(true);
String key = field.getName();
Object value = field.get(obj);
if (key != null && value != null && !TextUtils.isEmpty(key)) {
jsonObject.put(key, value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
return jsonObject.toString();
}
public static String listToJson(Collection objs) {
JSONArray jsonArray = new JSONArray();
for (Object obj : objs) {
JSONObject jsonObject = new JSONObject();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
String key = field.getName();
Object value = field.get(obj);
if (key != null && value != null && !TextUtils.isEmpty(key)) {
jsonObject.put(key, value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArray.put(jsonObject);
}
return jsonArray.toString();
}
}
反射获取对象的属性名和对应的值并转为json字符串
最新推荐文章于 2024-05-24 16:04:16 发布