将JSON写入文件

11

我有一个名为compositionJSON的类。该类有一个名为makeJSONObject的方法,用于创建JSON对象并将内容放入其中。以下是该类的代码。

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;
}

现在我创建了该类的一个实例并在另一个类中调用了该方法。之后,我希望将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变量,并在其上调用toString吗? - Chris Handy
可以,谢谢。现在可以正常工作了! - dudi
4个回答

12

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();
        }
    });

3
尝试编写一个简单的class,其中包含静态方法,用于将json对象保存到文件中并检索它: 代码:
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);

1

感谢 @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();
        }
    });

0
在 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();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接