【问题标题】:Write JSON to a File将 JSON 写入文件
【发布时间】:2016-04-13 09:05:14
【问题描述】:

我有一个类组合JSON。该类有一个调用 makeJSONObject 的方法,它创建一个 JSON-Object 并将内容放入其中。这是类的代码。

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 吗?
  • 好的,谢谢,现在可以正常使用了!

标签: android json filewriter


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试使用静态方法编写一个简单的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);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2012-11-13
          • 1970-01-01
          • 1970-01-01
          • 2022-08-22
          • 2018-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多