Javatpoint Logo
Javatpoint Logo

Convert JSON File to String in Java

In Java, we can easily convert JSON files to strings. Converting a JSON file into a string is done by reading bytes of data of that file.

In order to convert JSON files to string, we use the nio (non-blocking I/O) package(collection of Java programming language APIs that offer features for intensive I/O operations).

Suppose, we have a Sample.json file in the system that contains the following data:

We use the following steps to convert JSON data into a string:

  1. Import all the required classes such as Files, Paths, and Scanner.
  2. Take input from the user for the location and name.
  3. Create convertFileIntoString()
  4. In the convertFileIntoString() method, we use the get() method of the Paths class to get the file data.
  5. We use the readAllBytes() method of the Files class to read bytes data of the JSON files as a string.
  6. We store the returned result of the readAllBytes()and get()methods into a variable and return it to the main() method.
  7. In the main() method, we simply print the returned result of the convertFileIntoString()

Now, we convert or access data of the Sample.json file by using the above-discussed steps:

Note: In the above code, we convert the JSON file into a string and store it into the same type variable. So, we can perform all the string operations on the resultant variable.


Convert JSON File to String in Java

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA