Sunday, August 1, 2021

How to Convert JSON array to String array in Java - GSon example

A 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 a JSON object, here we will convert JSON array to String array or List in Java. As I said earlier, there are lots of open-source libraries out there that 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 the JSON data format and create a Java String array or List from JSON array representation.


Given the popularity of JSON as a lightweight alternative to XML to transfer data from Server to the 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 the 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 a JSON array to Java Array and vice-versa? Example

Here is the complete code example. This Java example uses the GSON library to create a List of String from JSON array and further Java standard library to convert List to an array. Instead of declaring JSON array in Code, which we did here for demonstration purposes, you can also read input from a file, database, or any URL. 

Code used to convert JSON array to java array will remain the same, except the getting input part. This JSON conversion example also shows the conversion of both String and numeric JSON array to the corresponding Java array.

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Java program to convert JSON array to String array in Java or List.
 *
 * @author Javin Paul
 */
public class JsonArraytoJavaList {

        private static Logger logger = Logger.getLogger(JsonArraytoJavaList.class);
       
        public static void main(String args[]){
                // Converting JSON String array to Java String array
                String jsonStringArray = "[\"JSON\",\"To\",\"Java\"]";
               
                //creating Gson instance to convert JSON array to Java array
                Gson converter = new Gson();
               
                Type type = new TypeToken<List<String>>(){}.getType();
                List<String> list =  converter.fromJson(jsonStringArray, type );
               
                //convert List to Array in Java
                String [] strArray = list.toArray(new String[0]);
               
                logger.info("Java List created from JSON String Array - example");
                logger.info("JSON String Array : " + jsonStringArray );
                logger.info("Java List : " + list);
                logger.info("String array : " + Arrays.toString(strArray));
               
                // let's now convert Java array to JSON array -        
                String toJson = converter.toJson(list);
                logger.info("Json array created from Java List : " + toJson);
               
                // example to convert JSON int array into Java array and List of integer
                String json = "[101,201,301,401,501]";
               
                type = new TypeToken<List<Integer>>(){}.getType();
                List<Integer> iList = converter.fromJson(json, type);
                Integer[] iArray = iList.toArray(new Integer[0]);      
               
                logger.info("Example to convert numeric JSON array to
                                  integer List and array in Java");
                logger.info("Numeric JSON array : " + json);
                logger.info("Java List of Integers : " + iList);
                logger.info("Integer array in Java : " + Arrays.toString(iArray));
               
                // Again, let's convert this Java int array back to Json numeric array
                String toJsonInt = converter.toJson(iList);
                logger.info("numeric JSON array create from Java collection : " 
                                          + toJsonInt);
        }
}

Output
Java List created from JSON String Array - example
JSON String Array : ["JSON","To","Java"]
Java List : [JSON, To, Java]
String array : [JSON, To, Java]
Json array created from Java List : ["JSON","To","Java"]
Example to convert numeric JSON array to integer List and array in Java
Numeric JSON array : [101,201,301,401,501]
Java List of Integers : [101, 201, 301, 401, 501]
Integer array in Java : [101, 201, 301, 401, 501]
numeric JSON array create from Java collection : [101,201,301,401,501]

Dependency
If you are not using Maven for dependency management then you can add  gson-2.2.2.jar into your application's classpath, Otherwise, you can add the 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 an 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 a very convenient method like toJson() and fromJSon() which just need type information to perform a conversion between JSON and Java.


Other JSON tutorials you may like to explore
  • How to convert a JSON  String to POJO in Java? (tutorial)
  • 3 Ways to parse JSON String in Java? (tutorial)
  • How to convert JSON array to String array in Java? (example)
  • How to convert a Map to JSON in Java? (tutorial)
  • How to use Google Protocol Buffer in Java? (tutorial)
  • How to use Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST and RESTful Web Services (books)


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.

1 comment :

cptully said...

1) This code will not run because you failed to import Type
2) Your code over runs the right margin, and there is tons of blank space on either side of the page - fix your layout!

Post a Comment