Home > Java > javaTutorial > How to convert collection to JSON array using JSON-lib API in Java?

How to convert collection to JSON array using JSON-lib API in Java?

WBOY
Release: 2023-08-20 19:09:04
forward
988 people have browsed it

如何使用Java中的JSON-lib API将集合转换为JSON数组?

net.sf.json.JSONArray is an ordered sequence of values. Its outer text form is a string enclosed in square brackets with values ​​separated by commas, and its inner form is an object with get() and opt( ) method, and the element() method that adds or replaces a value. These values ​​can be any of Boolean, JSONArray, JSONObject, Number, String and JSONNull objects.

We can convert a collection (List) to a JSON array as shown in the following example

Example

import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class ConvertCollectionToJsonArrayTest {
   public static void main(String[] args) {
      List<String> strList = Arrays.asList("India", "Australia", "England", "South Africa");
      JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(strList);
      System.out.println(jsonArray.toString(3)); //pretty print JSON
      List<Object><object> objList = new ArrayList<Object><object>();
      objList.add("List Data");
      objList.add(new Integer(50));
      objList.add(new Long(99));
      objList.add(new Double(50.65));
      objList.add(true);
      objList.add(new char[] {&#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;});
      jsonArray = (JSONArray)JSONSerializer.toJSON(objList);
      System.out.println(jsonArray.toString(3)); //pretty print JSON
   }
}
</object></object>
Copy after login

Output

[
   "India",
   "Australia",
   "England",
   "South Africa"
]
[
   "List Data",
   50,
   99,
   50.65,
   true,
      [
      "X",
      "Y",
      "Z"
   ]
]
Copy after login

The above is the detailed content of How to convert collection to JSON array using JSON-lib API in Java?. For more information, please follow other related articles on the PHP Chinese website!

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