- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we convert a list to the JSON array in Java?
The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values.
We can convert a list to the JSON array using the JSONArray.toJSONString() method and it is a static method of JSONArray, it will convert a 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"); // 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"]
Advertisements
To Continue Learning Please Login
Login with Google