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();
}
}
}
JSON 1. Overview Gson is a Java library that allows us to convert Java Objects into a JSON representation. We can also use it the other way around, to convert a JSON string to an equivalent Java object. In this quick tutorial, we'll find out how to save various Java data types as a JSON in a file. 2. Maven Dependencies
Saving Data to a JSON File We'll use the toJson (Object src, Appendable writer) method from the Gson class to convert a Java data type into JSON and store it in a file. The Gson () constructor creates a Gson object with default configuration:
We'll use the toJson (Object src, Appendable writer) method from the Gson class to convert a Java data type into JSON and store it in a file. The Gson () constructor creates a Gson object with default configuration: Now, we can call toJson () to convert and store Java objects.
In order to tweak the default Gson configuration settings, we can utilize the GsonBuilder class. This class follows the builder pattern, and it's typically used by first invoking various configuration methods to set desired options, and finally calling the create () method:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With