So here we will use JSON to communicate between two programs called Java and Node.js. We can use a common text format to communicate, but text format will contain a lot of complexities. However, JSON is lightweight and easy to use. JSON is language-independent and hence can be used by any programming language.
Serialization using Java: Serialization is the process of converting programming data to JSON text. In Java, there is no inbuilt library for JSON readers. We need to either add a dependency in our grade project or download the jar file. We had Jackson and simple-json libraries. Here simple-json library is used.
Let us generate a JSON file using java code as follows.
Java
import org.json.simple.JSONObject;import java.io.FileWriter;import java.io.IOException;public class MyClass { public static void main(String args[]) { JSONObject obj = new JSONObject(); obj.put("name", "Inshal Khan"); obj.put("Roll no", new Integer(42)); obj.put("cgpa", new Double(7.99)); try { FileWriter file = new FileWriter("E:/output.json"); file.write(obj.toJSONString()); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("JSON file created: "+jsonObject); }} |
Output:
JSON file created:{
"name":"Inshal Khan",
"Roll no":"42",
"cgpa":"7.99"}Deserialization using Node.js:
Javascript
'use strict'; const fs = require('fs'); fs.readFile('output.json', (err, data) => { if (err) throw err; let obj = JSON.parse(data); console.log(obj);}); console.log('File Reading completed'); |
Output:
JSON file created:{
"name":"Inshal Khan",
"Roll no":"42",
"cgpa":"7.99"}Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


