Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an java serialized file to json file

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.

like image 321
Jibin Mathew Avatar asked Sep 03 '25 07:09

Jibin Mathew


2 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();
          }
like image 72
Arpit Aggarwal Avatar answered Sep 04 '25 21:09

Arpit Aggarwal


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?

like image 39
pkozlov Avatar answered Sep 04 '25 21:09

pkozlov