Showing posts with label java list to json. Show all posts
Showing posts with label java list to json. Show all posts

Thursday, 18 May 2023

Java arraylist to json string

There are several ways to convert an ArrayList to a JSON string in Java. Here are two of the most common methods:

Using Gson

Gson is a popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Gson, you can use the following code:

Code snippet
import com.google.gson.Gson;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create a Gson object.
Gson gson = new Gson();

// Convert the ArrayList to a JSON string.
String json = gson.toJson(list);

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the following JSON string:

Code snippet
[
"Hello",
"World"
]

Using Jackson

Jackson is another popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Jackson, you can use the following code:

Code snippet
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create an ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();

// Convert the ArrayList to a JSON string.
try {
String json = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the same as the output of the previous code.