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-12-21 02:18:55 发布
本文介绍了一个用于将Java对象及集合转换为JSON字符串的实用工具类。该工具使用反射机制遍历对象的所有字段,并将其转化为对应的JSON格式。适用于快速集成JSON序列化的场景。

1927

被折叠的 条评论
为什么被折叠?



