Home > Java > javaTutorial > 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
Release: 2023-09-20 13:29:09
forward
1289 people have browsed it

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)
Copy after login

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);
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template