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

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

PHPz
PHPzforward
2023-08-25 17:17:02742browse

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

JSONArray is a sequence of values, the outer text is a string enclosed in square brackets with commas separating the values, and the inner text is a string with Object get() and opt() methods, we need to access these values ​​by index. The element() method for adding or replacing these values. Array is an object that stores multiple values ​​of the same type. It can hold primitive types and object references . We can convert a JSON array into an array using the toArray() method of the JSONArray class. This method generates an Object[] containing the contents of a JSONArray.

Syntax

public Object[] toArray()

Example

import java.util.Arrays;
import net.sf.json.JSONArray;
public class ConvertJSONArrayToArrayTest {
   public static void main(String[] args) {
      <strong>J</strong>SONArray jsonArray = new JSONArray()
                                .element("Raja Ramesh")
                                .element("115")
                                .element("Tutorials Point")
                                .element("Hyderabad")
                                .element(new String [] {"Java", "Testing", "Python"});
      String jsonStr = jsonArray.toString(3); //pretty print JSON
      System.out.println("JSON:\n" + jsonStr);
      Object[] array = jsonArray.toArray();
      System.out.println("-------------------------------------------------------------------");
      System.out.println("Array:\n" + Arrays.toString(array));
   }
}

Output

JSON:
[
   "Raja Ramesh",
   "115",
   "Tutorials Point",
   "Hyderabad",
   [
    "Java",
    "Testing",
    "Python"
   ]
]
----------------------------------------------------------------------------
Array:
[Raja Ramesh, 115, Tutorials Point, Hyderabad, ["Java","Testing","Python"]]

The above is the detailed content of How to convert JSON array to array using JSON-lib API in Java?. 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