Java原生JSONObject实现JSON串与Java对象互转

JSON串转Java对象

通用Object

public static <T> T jsonToObject(String json, Class<T> c)  {
    try {
        JSONObject jsonObject = new JSONObject(json);
        return (T) jsonToObject(jsonObject, c);
    } catch (JSONException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    } catch (InstantiationException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    } catch (IllegalAccessException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    }
    return null;
}

//一个静态类,将json对象,转化为java
private static Object jsonToObject(JSONObject jsonObject, Class c) throws IllegalAccessException, InstantiationException {
    Object obj = c.newInstance();
    Iterator it = jsonObject.keys();
    Field[] fields = c.getDeclaredFields();
    while (it.hasNext()) {
        String key = (String) it.next();
        //判断字段
        for (Field field : fields) {
            if (field.getName().equals(key)) {
                useSetter(c, field, jsonObject, obj);
                break;
            }
        }
    }
    return obj;
}

//调用该类的setter方法
private static void useSetter(Class c, Field field, JSONObject jsonObject, Object obj) {
    //获取字段类型以及字段名称
    Class fieldType = field.getType();
    String fieldName = field.getName();
    String methodName = toMethodName(fieldName);
    //System.out.println(methodName+"类型"+fieldType);
    //调用方法
    try {
        Method method = c.getMethod(methodName, fieldType);
        method.invoke(obj, jsonObject.get(fieldName));
    } catch (NoSuchMethodException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    } catch (Exception e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    }
}

//将fieldName转化为方法名称
private static String toMethodName(String name) {
    String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
    return methodName;
}

Map

public static Map<String, Object> jsonToMap(String json) {
    if (TextUtils.isEmpty(json)) {
        return null;
    }
    try {
        Map<String, Object> params = new HashMap<>();
        JSONObject jsonObject = new JSONObject(json);
        return jsonObjectToMap(jsonObject, params);

    } catch (JSONException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    }
    return null;
}

public static Map<String, Object> jsonObjectToMap(JSONObject jsonObject) {
    if (jsonObject == null) return null;
    Map<String, Object> params = new HashMap<>();
    return jsonObjectToMap(jsonObject, params);
}

private static Map<String, Object> jsonObjectToMap(JSONObject jsonObject, Map<String, Object> params) {
    if (jsonObject == null || params == null) {
        return params;
    }
    try {
        for (Iterator<String> iterator = jsonObject.keys(); iterator.hasNext();) {
            String key = iterator.next();
            if (!TextUtils.isEmpty(key)) {
                Object object = jsonObject.get(key);
                if (object instanceof JSONObject) {
                    params.put(key, jsonObjectToMap((JSONObject) object, params));
                } else {
                    params.put(key, jsonObject.get(key));
                }
            }
        }
    } catch (JSONException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    }
    return params;
}

Java对象转JSON串

通用Object

Map

public static String mapToJson(Map<String, String> map) {
    if (map.isEmpty()) return "{}";
    try {
        JSONObject json = new JSONObject();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            json.put(entry.getKey(), entry.getValue());
        }
        return json.toString();
    } catch (JSONException e) {
        NLog.e(TAG, Log.getStackTraceString(e));
    }
    return "{}";
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/25/java-jsonobject-implementation-for-json-string-and-java-object-conversion/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Java原生JSONObject实现JSON串与Java对象互转
JSON串转Java对象 通用Object public static <T> T jsonToObject(String json, Class<T> c) { try { JSONObject jsonObject = new ……
<<上一篇
下一篇>>
文章目录
关闭
目 录