Gson-从Json转换为类型化ArrayList <T>

使用Gson库,如何将JSON字符串转换ArrayList为自定义类的JsonLog?基本上,这JsonLog是由我的Android应用创建的各种日志(SMS日志,通话日志,数据日志)实现的界面,这ArrayList是所有这些的集合。我在第6行中不断收到错误消息。


public static void log(File destination, JsonLog log) {

    Collection<JsonLog> logs = null;

    if (destination.exists()) {

        Gson gson = new Gson();

        BufferedReader br = new BufferedReader(new FileReader(destination));

        logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6

        // logs.add(log);

        // serialize "logs" again

    }

}

看来编译器无法理解我指的是typed ArrayList。我该怎么办?


慕莱坞森
浏览 1784回答 3
3回答

摇曳的蔷薇

您可以使用TypeToken将json字符串加载到自定义对象中。logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

拉丁的传说

您的JSON示例为:{&nbsp; &nbsp; "status": "ok",&nbsp; &nbsp; "comment": "",&nbsp; &nbsp; "result": {&nbsp; &nbsp; "id": 276,&nbsp; &nbsp; "firstName": "mohamed",&nbsp; &nbsp; "lastName": "hussien",&nbsp; &nbsp; "players": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "player 1",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "player 2",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "player 3",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "player 4",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "player 5"&nbsp; &nbsp; ]}因此,如果您想将模块的数组列表保存在SharedPrefrences中,则:1-将使用此方法将返回的arraylist转换为json格式public static String toJson(Object jsonObject) {&nbsp; &nbsp; return new Gson().toJson(jsonObject);}2-将其保存在共享的偏好中PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));3-随时检索它从共享首选项中获取JsonStringString playersString= PreferencesUtils.getInstance(this).getString("players");4-再次将其转换为数组列表public static Object fromJson(String jsonString, Type type) {&nbsp; &nbsp; return new Gson().fromJson(jsonString, type);}ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new TypeToken<ArrayList<String>>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }.getType());如果您想解析对象的ArrayList,此解决方案也是可行的。希望通过使用Gson Library帮助您。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Android