[Java] How to convert an array into JSON string?
I want to convert a given array into JSON string, how can I do that in Java?
1 Answer
3 years ago by Eleven
We can use org.json
dependency to do this. Following is the dependency we need to add to pom.xml
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>
Then we can use the folowing code to generate a JSON string from array
import java.util.Arrays;
import org.json.JSONArray;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "red", "green", "blue", "orange", "maroon", "blue" };
System.out.println(new JSONArray(Arrays.asList(colors)).toString());
}
}
Output:
["red","green","blue","orange","maroon","blue"]
3 years ago by Karthik Divi