×

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

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.