Skip to content
Related Articles

Related Articles

Improve Article

How to communicate JSON data between Java and Node.js ?

  • Last Updated : 08 Apr, 2021

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"}



My Personal Notes arrow_drop_up
Recommended Articles
Page :