Android上的JSON - 序列化

Way*_*int 27 android json

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

谢谢

ale*_*dev 47

我们使用gson库.序列化就像调用一样简单

new Gson().toJson(obj)
Run Code Online (Sandbox Code Playgroud)

对于反序列化,

new Gson().fromJson(jsonStr, MyClass.class);
Run Code Online (Sandbox Code Playgroud)


Mar*_*man 25

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

要序列化

JSONObject json = new JSONObject();
json.put("key", "value");
// ...
// "serialize"
Bundle bundle = new Bundle();
bundle.putString("json", json.toString());
Run Code Online (Sandbox Code Playgroud)

并反序列化

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