从api获取数据并将其保存在文件中

时间:2019-02-15 07:58:02

标签: android json assets

我正在尝试从api获取数据并将其保存为Assets文件夹中的.json文件,以便以后可以访问。

我从api获取的数据是

[
 {
    "category" : "Top News",
    "data" : [
        {
            "title" : "Nashville Season 5 Premiere Set at CMT",
            "image_url" : "http://ia.media-imdb.com/images/M/MV5BMjA2NTE0NzkyMF5BMl5BanBnXkFtZTgwMjAwMzg5NjE@._V1._SY140_.jpg",
            "caption" : "The cancelled ABC country-music drama will make its CMT debut with a two-hour premiere on Thursday, January 5, at 9/8c, the cable network announced Wednesday",
            "time" : "1 hours ago"
        },
        {
            "title" : "Sarah Paulson Joins Ryan Murphy's FX Drama Feud as Geraldine Page",
            "image_url" : "http://ia.media-imdb.com/images/M/MV5BMTUzMTA3NjM4MV5BMl5BanBnXkFtZTcwNjk1NTAyMg@@._V1._SY140_.jpg",
            "caption" : "Ryan Murphy is taking a page from his successful playbook, casting frequent collaborator Sarah Paulson in his new FX anthology drama Feud.",
            "time" : "2 hours ago"
        },
        {
            "title" : "Ronald Reagan Biopic Draws ‘Soul Surfer’ Director Sean McNamara",
            "image_url" : "http://ia.media-imdb.com/images/M/MV5BMzEzOTk4OTQ2OF5BMl5BanBnXkFtZTYwMzkyODQ2._V1._SY140_.jpg",
            "caption" : "\"Soul Surfer\" Sean McNamara has signed to helm a Ronald Reagan biopic that’s set to start production next spring.",
            "time" : "3 hours ago"
        },
        {
            "title" : "Martin Lawrence Gets First Stand-Up Special in 14 Years at Showtime",
            "image_url" : "http://ia.media-imdb.com/images/M/MV5BMTczOTMwOTc1OF5BMl5BanBnXkFtZTgwNTc3MjY5NzE@._V1._SY140_.jpg",
            "caption" : "Martin Lawrence‘s first stand-up special in 14 years will air on Showtime next month, the network announced on Tuesday.",
            "time" : "10 hours ago"
        },
        {
            "title" : "Cmt Announces ‘Nashville’ Season 5 Premiere Date",
            "image_url" : "http://ia.media-imdb.com/images/M/MV5BMjgwMzg2ODgtZTkzYi00YTU0LThhYjMtMWM0Zjc0ZGFhMDViXkEyXkFqcGdeQXVyNjQxMDY5MjM@._V1._SY140_.jpg",
            "caption" : "\"Nashville\" is heading back to TV with a new network, new showrunners and a new year",
            "time" : "13 hours ago"
        }
    ]
}

我想将此数据保存在.json文件中。 我怎样才能做到这一点?? 这是我要创建的result 如果他们有其他方法请我引导我在卡片视图中的可扩展列表视图中进行操作。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您可以简单地使用SharedPreferences。

保存:

SharedPreferences sp = getSharedPreferences("your_pref_key", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("your_key", yourValue);
editor.commit();

供阅读:

SharedPreferences sp = getSharedPreferences("your_pref_key", Activity.MODE_PRIVATE);
 String yourJson = sp.getString("your_key","defaultValue");

如果要反序列化,请使用gson

Gson gson = new Gson();  
YourClass yourObject = gson.fromJson(yourJson, YourClass.class);