Tuesday, 30 March 2021

javax.json: Write json string to a file

Step 1: Create an output stream to a file.

OutputStream os = new FileOutputStream(FILE_TO_WRITE);

 

Step 2: Create a JsonWriter instance.

JsonWriter jsonWriter = Json.createWriter(os);

 

Step 3: Write the json object to the file using writer.

jsonWriter.writeObject(jsonObject);

 

Find the below working application.

 

WriteToFileDemo.java

package com.sample.app;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonWriter;

public class WriteToFileDemo {
        public static void main(String[] args) throws IOException {
                final String JSON_STRING = "{\n" + 
                                "    \"firstName\": \"Ram\",\n" + 
                                "    \"lastName\": \"Gurram\",\n" + 
                                "    \"id\": 32,\n" + 
                                "    \"male\": false,\n" + 
                                "    \"dateOfBirth\": \"10/01/1985\"\n" + 
                                "}\n";
                
                final String FILE_TO_WRITE = "/Users/Shared/json/emp.json";
                
                try (JsonReader reader = Json.createReader(new StringReader(JSON_STRING));
                                OutputStream os = new FileOutputStream(FILE_TO_WRITE);
                                JsonWriter jsonWriter = Json.createWriter(os);) {
                        
                        JsonObject jsonObject = reader.readObject();

                        jsonWriter.writeObject(jsonObject);
                }

        }

}

Run above application and open the file ‘/Users/Shared/json/emp.json’ to confirm the json content.

$ cat /Users/Shared/json/emp.json 
{"firstName":"Ram","lastName":"Gurram","id":32,"male":false,"dateOfBirth":"10/01/1985"}




 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment