簡體   English   中英

將JSON輸出到文件,然后重新輸入

[英]Output JSON to file, then input it back in

我正在為Android編寫一個應用程序,在該應用程序中,我需要將一些對象的信息輸出到文件中,以便在用戶關閉該應用程序時該文件仍然存在。等等。目前,我僅將這些對象輸出為字符串“ name”,每個都有自己的“價值”。 僅作為序言,我對Java和Android開發非常陌生,因此對任何愚蠢的錯誤深表歉意。

這是輸出JSON的代碼:

public static String outputFile(FileOutputStream out, String name, List<String> values)
{
    String outputString = "";
    outputString += "\"meals\":[\n";

    for (int i = 0; i < values.size(); i++)
    {
        outputString += "{\"" + name + "\": \"" + values.get(i) + "\"},\n"; //output: {"name":"value"}, for every element
    }
    outputString = outputString.substring(0, outputString.length()-2); //this takes off the newline char, and the last comma.
    outputString += "\n"; //add the newline character back on.
    outputString += "]";

    Gson g = new Gson();
    String s = g.toJson(outputString);

    try
    {
        out.write(s.getBytes());
        out.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return outputString; //debug only
}

然后,稍后,我使用它來輸入JSON並使用其各自的值解析每個對象:

public static List<String> inputFile(Context context, FileInputStream in, List<String> names)
{
    InputStreamReader inReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inReader);
    StringBuilder builder = new StringBuilder();
    String line;
    String tempJson = "";

    List<String> tempList = new ArrayList<>();

    try
    {
        while ((line = bufferedReader.readLine()) != null)
        {
            builder.append(line);
            String readJson = builder.toString();
            Gson readGson = new Gson();
            tempJson = readGson.fromJson(readJson, String.class);
        }
        in.close(); //close the file here?


        JSONObject jobj = new JSONObject(tempJson);

        for (int i = 0; i < names.size(); i++)
        {
            tempList.add(jobj.getString(names.get(i))); //this should add the JSON string stored at every index i in names.
        }

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return tempList;
    }
    catch (Exception e)
    {
        e.printStackTrace();

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return new ArrayList<>(Arrays.asList("File Input Error!")); //return a blank-ish list?
    }
}
}

因此,我敢肯定有一種更簡單的方法可以做到這一點。 也許我沒有像應該那樣使用gson? 任何幫助是極大的贊賞。

如果您只需要將列表存儲到磁盤以供以后使用,這是一種非常簡單的方法。

假設您有一個要存儲的字符串的ArrayList:

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");

您可以輕松地將這些存儲在應用程序的SharedPreferences中,這並不是真正的用戶首選項,而只是鍵/值槽,使用持久數據可以輕松訪問這些鍵/值槽。 您不能直接存儲ArrayList,但是可以存儲Set,因此我們首先需要將ArrayList轉換為Serializable Set:

HashSet<String> hashSet = new HashSet<>(arrayList);

然后,我們獲得該應用程序的SharedPreferences一個實例,並將新的HashSet保存到磁盤:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("name_of_the_preference_to_modify", hashSet);
editor.apply(); 

就是這樣! 准備好檢索數據時,首先需要獲取保存的HashSet:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
HashSet<String> hashSet = (HashSet<String>) sharedPreferences.getStringSet("name_of_the_preference_to_modify", new HashSet<String>());

只需將其轉換回ArrayList即可:

ArrayList<String> arrayList = new ArrayList<>(hashSet);

我認為這是保存列表的一種非常簡單干凈的方法。 而且您不必弄亂所有JSON。 希望能幫助到你!

試試這個方法:

public void saveObject(Object object) {
    String key = object.getClass().getSimpleName();
    Gson gson = new Gson() ;
    String objectJSON = gson.toJson(object);
    SharedPreferences sharedPreferences = context.getSharedPreferences("Pref name here", context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
    prefsEditor.putString(key, objectJSON);
}

public Object retrieveObject(Class objectClass){
    String key = objectClass.getSimpleName();
    Gson gson = new Gson();
    SharedPreferences sharedPreferences = context.getSharedPreferences("Pref name here", context.MODE_PRIVATE);
    String objectJSON = sharedPreferences.getString(key, "");
    Object object  = gson.fromJson(objectJSON, objectClass);
    return object;
}

第一個將對象轉換為json字符串,並將其保存到共享首選項。

第二個獲取字符串,將其轉換為json,然后返回對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM