json 时排除指定字段小工具1.0
demo:
public static void main(String[] args) {
TestJsonBean test = new TestJsonBean();
Object s1 = objs2JsonExcludeField(test);
System.out.println(s1);
}
测试类:
import com.biligame.access.annotaition.ExcludeField;
import java.util.HashMap;
public class TestJsonBean {
private int field1 = 1;
@ExcludeField
private String str1 = "123";
private HashMap<Integer, Integer> map = new HashMap<>();
{
map.put(1, 1);
map.put(2, 2);
}
public int getField1() {
return field1;
}
public void setField1(int field1) {
this.field1 = field1;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public HashMap<Integer, Integer> getMap() {
return map;
}
public void setMap(HashMap<Integer, Integer> map) {
this.map = map;
}
}
输出结果:
具体实现:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcludeField {
boolean isExclude() default true;
}
public static String obj2JsonUseExclude(Object object) throws IllegalAccessException {
Object o = objs2JsonExcludeField(object);
String resStr = null;
if (o instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) o;
resStr = jsonArray.toJSONString();
} else {
JSONObject jsonObject = (JSONObject) o;
resStr = jsonObject.toJSONString();
}
return resStr;
}
private static Object objs2JsonExcludeField(Object object) throws IllegalAccessException {
Object returnObj = null;
if (object instanceof List) {
JSONArray jsonArray = new JSONArray();
List list = (List)object;
for (Object obj : list) {
Object s = objs2JsonExcludeField(obj);
jsonArray.add(s);
}
returnObj = jsonArray;
} else if (object instanceof Map) {
returnObj = buildJsonObjByMap(object);
} else {
returnObj = buildJsonByObj(object);
}
return returnObj;
}
private static Object buildJsonByObj(Object obj) throws IllegalAccessException {
JSONObject jsonObject = new JSONObject();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
ExcludeField excludeField = f.getAnnotation(ExcludeField.class);
if (excludeField != null) {
continue;
}
Object o = f.get(obj);
Object sub = buildSubJsonObj(o);
jsonObject.put(f.getName(), sub);
}
return jsonObject;
}
private static Object buildJsonObjByMap(Object obj) throws IllegalAccessException {
JSONObject jsonObject = new JSONObject();
Map map = (Map) obj;
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
Object valObj = map.get(next);
Object subValObj = buildSubJsonObj(valObj);
jsonObject.put(String.valueOf(next), subValObj);
}
return jsonObject;
}
private static Object buildSubJsonObj(Object obj) throws IllegalAccessException {
boolean isBaseType = false;
try {
isBaseType = ((Class) obj.getClass().getField("TYPE").get(null)).isPrimitive();
} catch (NoSuchFieldException e) {
isBaseType = false;
}
boolean isOtherType = obj instanceof String;
if (isBaseType || isOtherType) {
return obj;
}
Object returnObj = objs2JsonExcludeField(obj);
return returnObj;
}