×

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON.

What is JSON?

JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and specifically designed for human-readable data interchange.

JSON is a data format and it is independent of language. Douglas Crockford first specified JSON in the early 2000s. 2013 saw the ECMA-404 standardization of JSON, and 2017 saw the publication of RCF 8259.

It supports nearly every language, framework, and library. JSON is an open standard for data exchange on the internet. It recognizes data structures such as objects and arrays. As a result, it's easy to write and read data from JSON.

Key-value pairs are used to represent data in JSON, and curly braces are used to hold objects with a colon following each name.

Use commas to separate key-value pairs. Each value in an array is separated by a comma and stored in square brackets.

Converting a JSON file into a string

JSON files are easily converted to strings in Java. Reading the file's bytes of data can convert a JSON file into a string.

The nio (non-blocking I/O) package, a collection of Java programming language APIs that provide features for intensive I/O operations, is used to convert JSON files to strings.

Filename: Sample.json

Assume we have a Sample.json file in the system that contains the data below:

 {  
  "Name" : "Virat",  
  "Mobile" : 89346724,  
  "Boolean" : true,  
  "Pets" : ["Lion", "Dog"],  
  "Address" : {  
    "Permanent address" : "INDIA - DELHI",  
    "current Address" : "INDIA - MUMBAI"  
  }  
}   

The following procedures are used to transform JSON data into a string:

  1. Bring in all necessary classes, including Files, Paths, and Scanner.
  2. Obtain the user's input for the name and location.
  3. Create the convertFileIntoString().
  4. The get() method of the Paths class is used to retrieve the file data in the convertFileIntoString() method.
  5. We read the bytes data from the JSON files as a string using the readAllBytes() method of the Files class.
  6. We return to the main() method, a variable that contains the output of the get() and readAllBytes() methods.
  7. We merely print the convertFileIntoString() method's returned result in the main() method.

Using the procedures described above, we can now convert or access the data in the Sample.json file:

Filename: ReadFileAsString.java

// import the necessary packages and classes
// To read the JSON file's bytes of data, we use classes from the nio package.
import java.nio.file.Files;  
import java.nio.file.Paths;  
import java.util.Scanner;  
// make a class called ReadFileAsString to transform a JSON file into a string.
public class ReadFileAsString {  
    // start the main() method
public static void main(String[] args) throws Exception {   //handle exception  
    // Declare the variables fileName, location, and file so that the user entered filename, location, and file data are each stored as a string, respectively.
    String fileName, file, location;  
    // Scanner class object creation
    Scanner sc = new Scanner(System.in) ;    
System.out.print("Enter the name of the file which you want to convert or access as string: ");    
        // take input from the user and initialize filName variable   
fileName = sc.nextLine();    
System.out.print("Enter the location of the "+fileName+" file: ") ;    
        //initialize the location variable after receiving input from the user.
location = sc.nextLine();    
        // close the scanner class obj  
sc.close();  
        // Make use of the convertFileIntoString() method to receive the file's data as a string. The data is saved into a file variable.
file = convertFileIntoString(location+"\\"+fileName);  
        // print the outcome, JSON data presented as a string.
System.out.println(file);  
    }  
    // To transform a JSON file into a string, create the convertFileIntoString() method.
public static String convertFileIntoString(String file)throws Exception  
    {  
    // Declare a variable in which the JSON data will be kept as a string and returned to the main() method.
    String result;  
    // create the result variable.
    // To retrieve the file data, we employ the Paths get() method.
    // To read byte data from the files, we use the readAllBytes() Files method.
    result = new String(Files.readAllBytes(Paths.get(file)));  
    // return the result to the main() method  
    return result;  
    }  
}  

Output:

Convert JSON File to String in Java

Note: In the code above, the JSON file is converted to a string and stored in a variable of the same type. Therefore, we can use the resultant variable to perform all string operations.


Related Topics

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.