Write JSON to a File

后端 未结 4 2012
南旧
南旧 2020-12-31 16:34

I have a class compositionJSON. The class has a method calls makeJSONObject, that creates a JSON-Object and put stuff in it. Here is the code of the class.

p         


        
4条回答
  •  独厮守ぢ
    2020-12-31 16:58

    Try this write a simple class with static methods to save and retrieve json object in a file :

    CODE :

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

    To save json in a file use RetriveandSaveJSONdatafromfile.objectToFile(jsonObj) and to fetch data from file use

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

提交回复
热议问题