Reputation: 1
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
?
Upvotes: 0
Views: 378
Reputation: 6067
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;
}
Upvotes: 0
Reputation: 5220
You can use @SerializedName annotations in Gson:
class Employee {
@SerializedName("EMP_ID")
private int empId;
@SerializedName("EMP_NAME")
private String empName;
}
Upvotes: 1