简体   繁体   中英

How to marshal/unmarshal Java to Json?

I want to convert Java POJO class into JSON. However I need to change the key name in JSON. For example:

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

Json should be : { "EMP_ID" : "101", "EMP_NAME" : "Tessst" }

I found Gson and other library to do this, but how can I change the JSON key name like map empId => EMP_ID ?

You can use @SerializedName annotations in Gson:

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

You can use reflection for that but the keys will remain same as variable name. I am doing same with bean class to make json from them.

Hope it will help.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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