在Android中写入JSON文件的问题

4sup72z8  于 2023-04-22  发布在  Android
关注(0)|答案(2)|浏览(188)

我试图写入一个json文件,它只是不工作,我没有得到任何错误,但没有任何变化的文件。
下面是我的代码的相关部分

try {
            //method1
            Gson gson = new Gson();
            String s = "gjsanhfhj";
            String path = this.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + "test.json";

            File file = new File(path);
            file.setWritable(true);

            gson.toJson(s,new FileWriter(file));

            //method2
            FileOutputStream outputStream;
            outputStream = openFileOutput(path, Context.MODE_PRIVATE);
            outputStream.write(s.getBytes());
            outputStream.close();

            //method3
            Writer output;
            output = new BufferedWriter(new FileWriter(file));
            output.write(s);
            output.close();

            Toast.makeText(this.getApplicationContext(), "check", Toast.LENGTH_SHORT).show();

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

我试了上面的3种方法,都不起作用,我找不到其他的方法
我试过这个

public class PlayerData {
    private int gold;
    private int wins;
    private int losses;

    public PlayerData(){
        gold = 0;
        wins = 0;
        losses = 0;
    }

            Gson gson = new Gson();
            String path = this.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + "test.json";
            File file = new File(path);
            file.setWritable(true);

            gson.toJson(new PlayerData(),new FileWriter(file));

不工作

3yhwsihp

3yhwsihp1#

试试这个我觉得很管用

private class myString {
    String str;
    public myString() {
        this.str = "Testing123...";
    }
}

Gson gson = new Gson();
    myString s = new myString();
    File file = new File(getApplicationContext().getFilesDir(), "Test.json");

    try {
        if(!file.exists())
            file.createNewFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] arr = gson.toJson(s).getBytes();
        fileOutputStream.write(arr);
        fileOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
yr9zkbsy

yr9zkbsy2#

Gson.toJson(Obj)用于将对象转换为Json-String,Json-String是一个键值对。Gson.toJson()以java对象作为参数,而你传递的是一个STRING值,我认为这是不正确的。例如,Employee类的对象,可以转换为json如下所示。

class Employee {
int empId;
String name;
String department;

{\fnSimHei\bord1\shad1\pos(200,288)}
现在,你可以打电话

gson.toJson(new Employee(100, "abc", "xyz"), new FileWriter(file));

所以,请再次检查您的要求。

相关问题