【问题标题】:JSON on Android - serializationAndroid 上的 JSON - 序列化
【发布时间】:2011-09-08 10:44:21
【问题描述】:

Android 有没有在序列化中使用 JSON 的简单示例?

谢谢

【问题讨论】:

    标签: android json


    【解决方案1】:

    为此,我们使用 gson 库。序列化就像调用一样简单

    new Gson().toJson(obj)
    

    对于反序列化,

    new Gson().fromJson(jsonStr, MyClass.class);
    

    【讨论】:

    • 反序列化:MyClass myClass = new Gson().fromJson(jsonStr, MyClass.class);
    【解决方案2】:

    如果您想避免在您的 Android 项目中使用另一个库来(反)序列化 JSON,您可以像我一样使用以下代码。

    序列化

    JSONObject json = new JSONObject();
    json.put("key", "value");
    // ...
    // "serialize"
    Bundle bundle = new Bundle();
    bundle.putString("json", json.toString());
    

    反序列化

    Bundle bundle = getBundleFromIntentOrWhaterver();
    JSONObject json = null;
    try {
        json = new JSONObject(bundle.getString("json"));
        String key = json.getString("key");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

    【讨论】:

    • 这很酷,但我无法想象它适用于更大的复杂 JSON 集
    • 你说得对,这适用于相当简单且相当小的 JSON。 :-)
    【解决方案3】:
        protected void onPostExecute(String results) {
            if (results!=null) {
                try {
                    Tec tec_m=new Tec();
    
                    tec_m=new Gson().fromJson(results, Technician.class);
    
                    ((AndroidActivity)activity).setData(tec_m);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    

    【讨论】:

      【解决方案4】:

      有一个简单的库来(反)序列化 JSON,与 android 自己的 json 库兼容。

      // deserialize a java bean to json object 
      JSONObject studentJson = JsonDeer.toJson(student);
      // serialize a java bean from json object
      Student student1 = JsonDeer.fromJson(studentJson,Student.class);
      

      library address

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多