将 JSON 写入文件

Write JSON to a File

我有class篇作文JSON。 class 有一个调用 makeJSONObject 的方法,它创建一个 JSON-Object 并将东西放入其中。这是 class.

的代码
public class CompositionJso extends JSONObject {



public JSONObject makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {

    JSONObject obj = new JSONObject() ;

    try {
        obj.put("title", title);
        obj.put("desc", desc);
        obj.put("imgPath", imgPath);
        obj.put("imgViewPath", imgView);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return obj;
}

现在我创建了这个 class 的实例并在另一个 class 中调用该方法。之后我想将 JSONObject 写入文件并将其保存在设备的 SD 卡上。这是代码:

 saveCompo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setName();
            createJSONFolder();
            CompositionJso obj = new CompositionJso();
            obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
            MyCompositionsListActivity.buildList();

            try {
                Writer output = null;
                File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
                output = new BufferedWriter(new FileWriter(file));
                output.write(obj.toString());
                output.close();
                Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();
        }
    });

文件保存成功,但是打开里面什么也没有。代码有什么问题?

在方法 makeJSONObject 中实例化一个新的 JSONObject。

此代码应该有效。

public void makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {

    try {
        this.put("title", title);
        this.put("desc", desc);
        this.put("imgPath", imgPath);
        this.put("imgViewPath", imgView);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

makeJSONObject 返回 JSONObject

您的代码应该是

saveCompo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setName();
            createJSONFolder();
            CompositionJso obj = new CompositionJso();
            JSONObject  jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
            MyCompositionsListActivity.buildList();

            try {
                Writer output = null;
                File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
                output = new BufferedWriter(new FileWriter(file));
                output.write(jsonObject.toString());
                output.close();
                Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();
        }
    });

谢谢@Chris Handy!我创建了一个 JSONObjectVariable 并将其分配给 makeJSONObject。这是我的最终代码:

saveCompo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setName();
            createJSONFolder();
            CompositionJso compositionJso = new CompositionJso();
            JSONObject obj;
            obj = compositionJso.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
            MyCompositionsListActivity.buildList();

            try {
                Writer output;
                File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
                output = new BufferedWriter(new FileWriter(file));
                output.write(obj.toString());
                output.close();
                Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();


            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();
        }
    });

尝试使用静态方法编写一个简单的 class 以在文件中保存和检索 json object :

代码:

public class RetriveandSaveJSONdatafromfile {

 public static String objectToFile(Object object) throws IOException {
    String path = Environment.getExternalStorageDirectory() + File.separator + "/AppName/App_cache" + File.separator;
    File dir = new File(path);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    path += "data";
    File data = new File(path);
    if (!data.createNewFile()) {
        data.delete();
        data.createNewFile();
    }
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
    objectOutputStream.writeObject(object);
    objectOutputStream.close();
    return path;
}

public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
    Object object = null;
    File data = new File(path);
    if(data.exists()) {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
        object = objectInputStream.readObject();
        objectInputStream.close();
    }
    return object;
}
} 

要在文件中保存 json 使用 RetriveandSaveJSONdatafromfile.objectToFile(jsonObj) 并从文件中获取数据使用

 path = Environment.getExternalStorageDirectory() + File.separator +   
 "/AppName/App_cache/data" + File.separator; 
 RetriveandSaveJSONdatafromfile.objectFromFile(path);