Home > Java > javaTutorial > 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
Release: 2023-08-25 17:17:02
forward
856 people have browsed it

如何使用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()
Copy after login

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

Output

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

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!

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