10

I'm trying to write json data to a json file.

After code execution no errors are thrown but the .json file is empty.

Please find below code and help on this

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

public class Test {
    public static void main(String[] args) throws JSONException {
        try {
            List<String> foo = new ArrayList<String>();
            foo.add("1");
            foo.add("2");
            foo.add("3");
            System.out.println("values :: "+foo);

            Writer writer = new FileWriter("operatorList.json");
            Gson gson = new GsonBuilder().create();
            gson.toJson(foo, writer);
        }
        catch(Exception e) {
            e.printStackTrace();            
        }
    }   
}
Tatranskymedved
  • 4,194
  • 3
  • 21
  • 47
Ramesh Raj
  • 185
  • 1
  • 2
  • 13
  • 1
    are you sure you are looking into the right file? – Jens Sep 01 '17 at 07:19
  • `gson.toJson(foo, writer);` problem is there. `toJson` returns a string, which is what you are meant to write to file. – Chol Nhial Sep 01 '17 at 07:20
  • 2
    @CholNhial No : `void toJson(Object src, Appendable writer)` it is a void. see the [documentation](https://google.github.io/gson/apidocs/com/google/gson/Gson.html#toJson-java.lang.Object-java.lang.Appendable-) – Jens Sep 01 '17 at 07:20
  • @CholNhial ,can you suggest me a better way for writing json data to a json file – Ramesh Raj Sep 01 '17 at 07:27
  • @Jens, yes the file is correct one – Ramesh Raj Sep 01 '17 at 07:27
  • @RameshRaj, there's nothing wrong with the way you are doing it, I just think you forgot to close the stream. Give that a try. – Chol Nhial Sep 01 '17 at 07:30
  • @CholNhial ,I tried it by closing it , but the issue remain same, – Ramesh Raj Sep 01 '17 at 07:38
  • Few things that can help you debug the issue. Replace filename with absolute filepath when creating the FileWriter object. Do a sysout or debug pointer to see if the List is indeed converting to JSON and no issues there. Finally try writer.flush() followed by writer.close(). – Himanshu Bhardwaj Sep 01 '17 at 07:39
  • I tried but it is not working by the way i 'm using eclipse , when i create json file it is showing error but when i uncheck JSON validation it went away – Ramesh Raj Sep 01 '17 at 07:49
  • @CholNhial I found something fishy , when i change the file location to (Writer writer = new FileWriter("operatorList.json")) then i got the required output – Ramesh Raj Sep 01 '17 at 07:54
  • @CholNhial but when i give file location as Writer writer = new FileWriter("operatorList.json"); it is not getting stored into the file , please suggest on this , i want to have the location in the same project module – Ramesh Raj Sep 01 '17 at 07:55
  • @Ramesh Raj, I recommend just using FileWriter, its not so different, but you won't be telling 'toJson()' to do the appending instead use '.append(str)' on FileWriter object to append the json to file. The constraint is with how list are serialized. – Chol Nhial Sep 01 '17 at 08:44
  • @CholNhial , the code is working fine , somehow the file location has the issue ,Writer writer = new FileWriter("operatorList.json") the location must be with the classpath as i'm running code in eclipse – Ramesh Raj Sep 01 '17 at 08:50
  • The location/file is being opened relative to the directory where you executed the jar/.class. is there a reason you cant just hardcode the path inside the code? – Chol Nhial Sep 01 '17 at 09:02

2 Answers2

39

You are in the right way, just flush() and close() the writer, like this:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Writer;

import java.util.ArrayList;

import java.util.List;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonObject;

public class Test {

public static void main(String[] args) throws JSONException {    
    try{
        List<String> foo = new ArrayList<String>();
        foo.add("1");
        foo.add("2");
        foo.add("3");
        System.out.println("values :: "+foo);
        Writer writer = new FileWriter("operatorList.json");
        Gson gson = new GsonBuilder().create();
        gson.toJson(foo, writer);
        writer.flush(); //flush data to file   <---
        writer.close(); //close write          <---
    }catch(Exception e){
        e.printStackTrace();
    }    
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Steve_Angel
  • 579
  • 5
  • 4
  • 3
    Thank you! This really helped. I'm new to Java, and all the examples I've seen so far don't mentioned to flush. – ScubaManDan Aug 20 '18 at 09:43
  • 3
    Indeed, flushing and closing the writer solved my issue! Thank you +1. – SergioMP Apr 26 '19 at 12:02
  • Thank you so much! I'm using the Java 8 version (`try (FileWriter fw = new FileWriter(myFile)) {}`) and I had the same problem: My Android app reads a json text from file, then sometimes changes a couple of things/saves it back to file and later on reads it again (amongst other things). I checked the file afterwards and it had text written in it but my app still always complained that it didn't (reading the second time). Flushing the writer fixed this. :) Afaik, `close()` isn't necessary afterwards if you use Java 8's `try` version (probably won't hurt though). – Neph Apr 09 '20 at 11:08
0

My previous answer didn't help you. Try this one. The issue seems to be with serialising/deserializing lists. I hope it helps, you should just be able to run that.

public class Main {



public static void main(String[] args) {


    List<String> operators = new ArrayList<>();

    operators.add("Bruce Lee");
    operators.add("Jackie Chan");
    operators.add("Chuck Norris");

    Type listOfStringObjects = new TypeToken<List<String>>(){}.getType();

    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(operators, listOfStringObjects);

    try(FileWriter writer = new FileWriter("operatorList.json")) {
        writer.append(json);
        System.out.println("Successfully serialized operators!");
    }catch (IOException ex) {
        System.err.format("An IO Exception was occurred: %s%n", ex);
        System.exit(-1);
    }

    // Deserializing
    System.out.println("Deserializing operators from JSON (Reading back)...");
    try(BufferedReader reader = new BufferedReader(new FileReader("operatorList.json"))) {
        StringBuilder jsonData = new StringBuilder();
        String line;
        while((line = reader.readLine()) != null) {
            jsonData.append(line);
        }
        List<String> operatorsRead = gson.fromJson(jsonData.toString(), listOfStringObjects);

        for(String operator : operatorsRead) {
            System.out.println("Operator: " + operator);
        }
    }catch (Exception ex) {
        System.err.format("An IO Exception was occurred: %s%n", ex);
    }
}
}
Chol Nhial
  • 1,327
  • 1
  • 10
  • 25
  • 1
    or use java7 syntax: try (Writer writer = new FileWriter("operatorList.json")) { Gson gson = new GsonBuilder().create(); gson.toJson(foo, writer); } – Tim Sep 01 '17 at 07:26
  • I tried by closing the writer ,writer.close() but the issue remains the samw – Ramesh Raj Sep 01 '17 at 07:30
  • @Chol Nhial , please find my comments above , there is some issue while giving location of the file , my code is working properly – Ramesh Raj Sep 01 '17 at 08:00