Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write JSON to a File

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.

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

Now I create a instance of this class and call the method in another class. After that I want to write the JSONObject to file and save it on the sd card on device. Here is the code:

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

The file is saving successfully but if I open it, there is nothing inside. What is wrong with the code?

like image 333
dudi Avatar asked Jan 08 '16 16:01

dudi


People also ask

How do I write JSON in Notepad?

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON. Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as . JSON file, you have to just select the location of the file.

Is a JSON file just a text file?

The Javascript Object Notation(JSON) is used to transfer or exchange information on the internet. JSON is just the plain text written as a javascript object.


2 Answers

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);
like image 172
Kapil Rajput Avatar answered Nov 15 '22 21:11

Kapil Rajput


makeJSONObject is returning JSONObject

Your code should be

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();
        }
    });
like image 27
Parag Chauhan Avatar answered Nov 15 '22 19:11

Parag Chauhan