Tuesday 30 March 2021

javax.json: Read json from a file

Step 1: Create input stream for the file.

InputStream fis = ReadFromFileDemo.class.getClassLoader().getResourceAsStream(JSON_FILE);

 

Step 2: Get JsonReader instance from the inputstream.

JsonReader jsonReader = Json.createReader(fis)

 

Step 3: Get JsonObject from readObject method of JsonReader

JsonObject jsonObject = jsonReader.readObject();

 

Find the below working application.

 

ReadFromFileDemo.java

package com.sample.app;

import java.io.IOException;
import java.io.InputStream;

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

public class ReadFromFileDemo {
        public static final String JSON_FILE = "employee.json";

        public static void main(String[] args) throws IOException {

                try (InputStream fis = ReadFromFileDemo.class.getClassLoader().getResourceAsStream(JSON_FILE);
                                JsonReader jsonReader = Json.createReader(fis)) {

                        JsonObject jsonObject = jsonReader.readObject();

                        String result = jsonObject.toString();
                        System.out.println(result);

                }

        }
}

 

Output

{"firstName":"Ram","lastName":"Gurram","id":32,"male":false,"dateOfBirth":"10/01/1985"}

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment