あなたはそのためにリフレクションを使用することができますが、キーは変数名と同じままになります。 jsonを作るためにbeanクラスと同じことをやっています。
希望すると助かります。
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;
}
ありがとう:)この作品.. – Sid