Wednesday, 24 April 2013

How to read a JSON object from file using Java

Reading a JSON file Using Java



package com.gaurav.coreexamples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadJsonObjectFromFileUsingJava {
                public static void main(String... args) throws IOException {

                                BufferedReader reader = new BufferedReader(new FileReader(
                                                                "C:\\JsonData.json"));

                                StringBuilder sb = new StringBuilder();
                                String line = reader.readLine();

                                while (line != null) {
                                                sb.append(line + "\n");
                                                line = reader.readLine();
                                }
                                reader.close();
                                String data = sb.toString();

                                System.out.println(data);

                }
}

Result:-


Note:- Here i am reading a file named "JsonData.json" available in C:/ drive, in that file, below content is available:-

{"age":25,"name":"Gaurav","relations":["WIFE","FATHER","MOTHER","SISTER"]}
{"age":22,"name":"Kate","relations":["HUSBAND","MOTHER","BROTHER"]}
{"age":26,"name":"Julia","relations":["FATHER","MOTHER","SON"]}

Note:- Using this way, we can read any type of file and read any data available in buffer, we can also read HttpServletRequest data using the above code.

1 comment: