Home  >  Article  >  Java  >  In Java, how can we convert a list to a JSON array?

In Java, how can we convert a list to a JSON array?

WBOY
WBOYforward
2023-09-20 13:29:091218browse

In Java, how can we convert a list to a JSON array?

JSON is a lightweight, text-based and language independent data exchange Format. JSON can represent two structured types, such as object and array. An object is an unordered collection of key/value pairs, and an array is an ordered sequence of values.

We can use the JSONArray.toJSONString() method to convert the list into a JSON array, which is a static JSONArray method , which converts the list to JSON text , and the result is a JSON array.

Syntax
public static java.lang.String toJSONString(java.util.List list)

Example

import java.util.*;
import org.json.simple.*;
public class ConvertListToJSONArrayTest {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("India");
      list.add("Australia");
      list.add("England");
      list.add("South Africa");
      list.add("West Indies");
      list.add("Newzealand");
<strong>     </strong> // this method converts a list to JSON Array
      String jsonStr = JSONArray.toJSONString(list);
      System.out.println(jsonStr);
   }
}

Output

["India","Australia","England","South Africa","West Indies","Newzealand"]

The above is the detailed content of In Java, how can we convert a list to a JSON array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete