繁体   English   中英

如何将Java编组/解组到Json?

[英]How to marshal/unmarshal Java to Json?

我想将Java POJO类转换为JSON。 但是我需要在JSON中更改密钥名称。 例如:

class Employee {
    private int empId;
    private String empName;
}

杰森应该是: { "EMP_ID" : "101", "EMP_NAME" : "Tessst" }

我发现Gson和其他库可以做到这一点,但是如何更改JSON密钥名称(如map empId => EMP_ID呢?

您可以在Gson中使用@SerializedName批注:

class Employee {
    @SerializedName("EMP_ID")
    private int empId;
    @SerializedName("EMP_NAME")
    private String empName;
}

您可以为此使用反射,但是键将保持与变量名相同。 我正在用bean类做同样的事情,从他们做json。

希望它会有所帮助。

public static String getRequestJsonString(Object request,boolean withNullValue) {

    JSONObject jObject = new JSONObject();

    try {
        if (request != null) {
            for (Map.Entry<String, String> row : mapProperties(request,withNullValue).entrySet()) {

                jObject.put(row.getKey(), row.getValue());
            }
        }

        Log.v(TAG, jObject.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

   return jObject.toString();
}


public static Map<String, String> mapProperties(Object bean,boolean withNullValue) throws Exception {
    Map<String, String> properties = new HashMap<>();
    try {
        for (Method method : bean.getClass().getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers())
                    && method.getParameterTypes().length == 0
                    && method.getReturnType() != void.class
                    && method.getName().matches("^(get|is).+")
                    ) {
                String name = method.getName().replaceAll("^(get|is)", "");
                name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");

                Object objValue = method.invoke(bean);

                if (objValue != null) {
                    String value = String.valueOf(objValue);
                    //String value = method.invoke(bean).toString();
                    properties.put(name, value);
                } else {

                    if (withNullValue)
                    {
                        properties.put(name, "");
                    }
                }

            }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return properties;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM