package com.tobiasy.toolkit.json; import com.alibaba.fastjson.JSONObject; import com.tobiasy.toolkit.common.Generate; import com.tobiasy.toolkit.enums.BeanPrefix; import com.tobiasy.toolkit.reflect.ReflectUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Set; import static com.tobiasy.toolkit.common.StringUtils.capitalizeCase; /** * @author tobiasy * 若需要解析对象属性中的Object属性,在该对象中配置@JsonObjectMark或者extends JsonObjectMark即可 */ public class JsonUtils { public static String toJson(Object object) { return new JsonObject(object).toJson(); } public static <T> T parseJson(String toJson, Class<T> clazz) { T t = null; JSONObject parse = null; try { t = clazz.newInstance(); parse = (JSONObject)JSONObject.parse(toJson); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } Set<String> set = parse.keySet(); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String key = iterator.next(); Object o = parse.get(key); try { JSONObject json = (JSONObject) JSONObject.parse(o.toString()); Field field = clazz.getField(key); o = parseJson(json.toJSONString(), field.getType()); } catch (Exception e) {} Method method = ReflectUtils.findMethod(clazz, Generate.toGetter(key)); ReflectUtils.invoke(t, Generate.toSetter(key), method.getReturnType(), o); } return t; } }