如何在您的 android 项目中有效使用 JSONObject

How to use JSONObject effective in your android project

最近我的项目有json的需求,但是我从来没有用过json,所以我想知道如何使用json才有效。 我使用 Volley 作为我的网络库,默认支持 json,知道我可以获得 JSONObject 或 JSONArray 响应,并且可以通过以下方法获取数据:

String name = response.optString("name"); 

显然这不是一个好主意,我想生成java class 作为我的响应数据,使用模型class 包装JSONObject 或使用gson、jackson 生成a java class,谁能分享一下经验?谢谢。

关于 JSON+Android 有数百万的实现和用例,但以下是常见的方法。

  1. 我使用 gson 是为了 de/serialize 一个对象,如下所示。对我来说,它比序列敏感 Parcelable 转换更可靠。

     public static String toJson(Object obj){
         Gson gson = new Gson();
         return gson.toJson(obj);
     }
    
     public static Object fromJson(String json, Class clazz) 
     {
         Gson gson = new Gson();
         return gson.fromJson(json, clazz);
     }
    
  2. 在 json 与服务器通信的情况下,Retrofit 给出整洁的 json i/o 处理。

  3. 或者,我使用 loopj async library 并实现静态 JSON 反序列化器,因为所有属性都可以由我自己处理。

     public class Question {
         public int count;
         public String text;
         public Date generateTime;
    
         public static Question FromJson(JSONObject jsonObject) throws JSONException {
             Question result = new Question();
             result.category = jsonObject.optInt("Count");
             result.text = jsonObject.optString("Text", "");
             result.generateTime = DateTime.parse(jsonObject.optString("GenerateTime")).toDate() : new Date();
             return result;
         }
     }