I have a java class already serialized and stored as .ser format file but i want to get this converted in json file (.json format) , this is because serialization seems to be inefficient in terms of appending in direct manner, and further cause corruption of file due streamcorruption errors. Is there a possible efficient way to convert this java serialized file to json format.
-
If i understand you correctly, first you would like to serialize data to file, and then you would like to convert serialized data into JSON because serialization is inefficient ? But you already did serialization and paid any price that comes with it that way. – John Jun 21 '15 at 17:36
3 Answers
You can read the .ser
file as an InputStream
and map the object received with key/value
using Gson and write to .json
file
InputStream ins = new ObjectInputStream(new FileInputStream("c:\\student.ser"));
Student student = (Student) ins.readObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(student );
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

- 27,626
- 16
- 90
- 108
-
Manually mapping the object properties sounds like a lot of work. Take a look at Jackson or Gson which provide automatic POJO <-> JSON conversion. – dnault Jun 21 '15 at 17:55
-
Correct, manual mapping will be tough in case of lot of fields, so updated the code for automatic conversion from POJO to `JSON`. – Arpit Aggarwal Jun 21 '15 at 18:02
There is no standard way to do it in Java and also there is no silver bullet - there are a lot of libraries for this. I prefer jackson https://github.com/FasterXML/jackson
ObjectMapper mapper = new ObjectMapper();
// object == ??? read from *.ser
String s = mapper.writeValueAsString(object);
You can see the list of libraries for JSON serialization/deserialization (for java and not only for java) here http://json.org/
this is because serialization seems to be inefficient in terms of appending in direct manner
Not sure if JSON is the answer for you. Could you share with us some examples of data and what manipulations you do with it?

- 746
- 5
- 17
You can try Google Protocol Buffers as alternative to Java serialization and JSON.
In my answer in topic bellow there is an overview of what GPB is and how to use, so you may check that and see if it suits you: