Java開発–オブジェクトからJSON文字列へ変換する方法
JAVAコード:
public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
if(obj==null){
return “null";
}
String jsonStr = “{“;
Class<?> cla = obj.getClass();
Field fields[] = cla.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.getType() == long.class){
jsonStr += “\""+field.getName()+"\":"+field.getLong(obj)+",";
}else if(field.getType() == double.class){
jsonStr += “\""+field.getName()+"\":"+field.getDouble(obj)+",";
}else if(field.getType() == float.class){
jsonStr += “\""+field.getName()+"\":"+field.getFloat(obj)+",";
}else if(field.getType() == int.class){
jsonStr += “\""+field.getName()+"\":"+field.getInt(obj)+",";
}else if(field.getType() == boolean.class){
jsonStr += “\""+field.getName()+"\":"+field.getBoolean(obj)+",";
}else if(field.getType() == Integer.class||field.getType() == Boolean.class
||field.getType() == Double.class||field.getType() == Float.class
||field.getType() == Long.class){
jsonStr += “\""+field.getName()+"\":"+field.get(obj)+",";
}else if(field.getType() == String.class){
jsonStr += “\""+field.getName()+"\":\""+field.get(obj)+"\",";
}else if(field.getType() == List.class){
String value = simpleListToJsonStr((List<?>)field.get(obj),claList);
jsonStr += “\""+field.getName()+"\":"+value+",";
}else{
if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
String value = ObjToJsonStrFunc(field.get(obj),claList);
jsonStr += “\""+field.getName()+"\":"+value+",";
}else{
jsonStr += “\""+field.getName()+"\":null,";
}
}
}
jsonStr = jsonStr.substring(0,jsonStr.length()-1);
jsonStr += “}";
return jsonStr;
}