Pages

JSON array is an ordered collection of values, which are enclosed within brackets e.g. [] and separated by a comma. In this Java tutorial, we will convert JSON Array to String array in Java and subsequently create JSON from Java String Array. This tutorial is similar to our last article in JSON about How to convert JSON object to Java object, instead of JSON object, here we will convert JSON array to String array or List in Java. As I said earlier, there are lot's of open source library out there which can help to parse JSON data format and we have already seen Jackson library in our last example. In this tutorial, we will use GSON to parse JSON data format and create Java String array or Listfrom JSON array representation. Given the popularity of JSON as a lightweight alternative to XML to transfer data from Server to client in web applications, it's becoming imperative to know about JSON data format and parsing JSON string, much like parsing XML documents and knowing about different XML parsers e.g. DOM or SAX. Since Java application development is more about reusing existing library, then coding yourself, its important to know what is available, and which library other programmers are using. So far we have seen Jackson library, and here we will explore another one called GSon.

How to convert JSON array to Java Array and vice-versa

Here is the complete code example. This Java example uses GSON library to create List of String from JSON array and further Java standard library to convert List to array. Instead of declaring JSON array in Code, which we did here for demonstration purpose, you can also read input from file, database or any URL. Code used to convert JSON array to java array will remain same, except the getting input part. This JSON conversion example, also shows conversion of both String and numeric JSON array to corresponding Java array.

If you are not using Maven for dependency management then you can addgson-2.2.2.jar into your application's classpath, Otherwise you can add following dependency in your projects pom.xml

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.2.2</version>

</dependency>

That's all on How to convert JSON array to Java array and collection. We have seen example of converting JSON String array to List of String and String array in Java, similarly converting numeric JSON array to List of Integer and integer array in Java. GSON library provides very convenient method e.g. toJson() and fromJSon() which just need type information to perform conversion between JSON and Java.

P.S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's REST with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real world concepts you will learn from the course.