351
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:
- Import all the required classes such as Files, Paths, and Scanner.
- Take input from the user for the location and name.
- Create convertFileIntoString()
- In the convertFileIntoString() method, we use the get() method of the Paths class to get the file data.
- We use the readAllBytes() method of the Files class to read bytes data of the JSON files as a string.
- We store the returned result of the readAllBytes()and get()methods into a variable and return it to the main() method.
- 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:
ReadFileAsString.java
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.
Output:
Next TopicConvert Milliseconds to Date in Java