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;
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
  • 2021-12-19
  • 2021-08-05
  • 2021-12-02
  • 2022-01-12
猜你喜欢
  • 2021-11-26
  • 2022-12-23
  • 2021-08-05
  • 2022-01-10
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
相关资源
相似解决方案