Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

How to convert array to JSON in Java? Example Tutorial

Before converting an array to Json. It is good to have a good understanding of an array and what JSon is.  

What then is an Array? An array is a data structure in java that holds values of the same type with its length specified right from creation time. Or you can say an array is a collection of similar type of elements which has contiguous memory location.

Oftentimes you may have to work on a task whereby you will have to store a large number of values during the execution of a program. for instance, you need to read 50 numbers, calculate their average, and find out how many numbers are above the average, and how many numbers are below average.

Your program first reads the numbers and calculates their average, then compares each number with the average to determine whether it is above the average or below. To accomplish this task, the numbers must all be stored in variables. 

You have to declare 50 variables and repeatedly write almost identical code 50 times. Writing a program this way would be impractical. So, how do you solve this problem? An efficient, organized approach is needed. 

Java and most other high-level languages provide a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. In the present case, you can store all 50 numbers into an array and access them through a single array variable.



How do you create an array in Java?


  1. Int [] num = new int[5]


In these previous lines of codes, you are creating an array of integer numbers with the variable name "num" and you are assigning it to a new integer of length 5. meaning that the items coming can only be an integer and it has to be 5. 

Anything that does not correlate with what you have specified results in compilation error. In an array you can access each element through its index, the index number starts from zero. So the first element is index num 0, the second element is index num 1, and the third element is index num 2, and on and on as you can see above.

If you want to get the total number of the index you will do length - 1 because the length you specified at creation time is 5 and because the indexes start from 0, not 1. so, the length of the indexes is 4.





What is JSON?

Now, let’s move to JSON? It is a JavaScript object notation that is used to transfer data from the server across the web. It is self-describing and easy to understand. is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of key-value pairs and arrays (or other serializable values). 

It is a common data format with diverse uses in electronic data interchange, including that of web applications with servers. JSON is a language-independent data format.

 It was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data. JSON filenames use the extension .json.

Fig 1.0: How Json works with the server.

In JSon, note that:

·Data is in name/value pairs

·Data is separated by commas

·Curly braces hold objects

·Square brackets hold arrays

An Array is a type of data Structure, so Imagine you have an array with the element of type Strings and you want to convert it to javaScript object notation (Json). The Implementation gives how to do that.






How to convert array to JSON in Java

Now we would be solving a problem which is converting an array into json in java.

```

  1. public class ArrayToJson {
  2. public static void main(String[] args) {
  3. int[] numbers = {1, 1, 2, 3, 5, 8, 13};
  4. String[] fruits = {"Apple", "Cucumber", "Pineapple", "Grape", "Orange", "Pawpaw", "Water melon"};
  5. // Create a new instance of Gson
  6. Gson gson = new Gson();
  7. // Convert numbers array into JSON string.
  8. .String numbersJson = gson.toJson(numbers);
  9. // Convert strings array into JSON string
  10. String fruitsJson = gson.toJson(fruits);
  11. System.out.println("numbersJson = " + numbersJson);
  12. System.out.println(" fruitsJson = " + fruitsJson);
  13. }
  14. }

```

EXPLANATION:

Line 1 declares the class ArrayToJson and with the main method in line 2. an array of numbers of type int was initialized with a set of values in line 3 and in line 4, arrays of fruits of type String was initialized too. Line 6 creates a new instance of Gson


Note: Gson is a class in java with its inbuilt methods. So gson was created as an instance of Gson. Line 8 created a variable with the name "numbersJson"  and the method toJson was called which takes in numbers as argument and was stored in the variable that was just created. The same thing applies to the fruits too. Line 11 and 12 prints the results out.

OUTPUT:

numbersJson = [1,1,2,3,5,8,13]

daysJson = ["Apple", "Cucumber", "Pineapple", "Grape", 
"Orange", "Pawpaw", "Water melon"]


That's all about how to convert an array to JSON in Java. You can see by using Gson API and library it's quite easy to convert any type of Java array to JSON messages. 


Other Java JSON tutorials you may like

  • How to convert JSON String to Java Object? (example)
  • How to use Google Protocol Buffer in Java? (tutorial)
  • How to convert JSON array to String array in Java? (answer)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • How to parse large JSON files using Jackson Streaming API? (example)
  • 5 Books to Learn REST and RESTful Web Services (books)
  • How to consume JSON from RESTful Web Services using RestTemplate of Spring? (tutorial)
  • What is the purpose of different HTTP methods in REST? (see here)
  • Top 5 Courses to learn REST with Java? (courses)
  • How to convert JSON to HashMap and vice-versa (tutorial)


Thanks for reading this article. If you like this article then please share it with your friends and colleagues, if you have any questions or feedback then please drop a comment.

P.S. - If you want to learn more about the advanced topic in Java, I also suggest you join these Free Java Programming courses, which cover several advanced Java features like JSON, RESTFul Web Services, JAXB, JDBC, etc. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.