Convert class into a JSONObject

拟墨画扇 提交于 2019-12-03 03:42:32

I found that the following works with GSON:

    User = new User();
    Gson gson = new Gson();
    String jsonString = gson.toJson(user);
    try {
        JSONObject request = new JSONObject(jsonString);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

This is not type safe, however.

Here is a crude example you can use to use Reflection to build the JSONObject..

Warning it's not pretty and does not contain really type-safety.

public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
    JSONObject object = new JSONObject();

    Class<?> objClass = obj.getClass();
    Field[] fields = objClass.getDeclaredFields();
    for(Field field : fields) {
        field.setAccessible(true);
        Annotation[] annotations = field.getDeclaredAnnotations();
        for(Annotation annotation : annotations){
            if(annotation instanceof SerializedName){
               SerializedName myAnnotation = (SerializedName) annotation;
               String name = myAnnotation.value();
               Object value = field.get(obj);

               if(value == null)
                  value = new String("");

               object.put(name, value);
            }
        }
    }   

    return object;
}

Here is an example usage:

User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));

Output

{
   "id": "",
   "name": "",
   "email": ""
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!