JSONArray

Introduction

In JSON, JSONArray represents an array, enclosed by square brackets, with each element separated by a comma. A JSONArray looks like this:

["value1","value2","value3"]

Usage

Creation

// Method 1
JSONArray array = JSONUtil.createArray();
// Method 2
JSONArray array = new JSONArray();

array.add("value1");
array.add("value2");
array.add("value3");

// Convert to JSONArray string
array.toString();

Parsing from Bean List

First, define the bean:

@Data
public class KeyBean {
    private String akey;
    private String bkey;
}
KeyBean b1 = new KeyBean();
b1.setAkey("aValue1");
b1.setBkey("bValue1");
KeyBean b2 = new KeyBean();
b2.setAkey("aValue2");
b2.setBkey("bValue2");

ArrayList<KeyBean> list = CollUtil.newArrayList(b1, b2);

// [{"akey":"aValue1","bkey":"bValue1"},{"akey":"aValue2","bkey":"bValue2"}]
JSONArray jsonArray = JSONUtil.parseArray(list);

// aValue1
jsonArray.getJSONObject(0).getStr("akey");

Parsing from JSON String

String jsonStr = "[\"value1\", \"value2\", \"value3\"]";
JSONArray array = JSONUtil.parseArray(jsonStr);

Converting to a List of Beans

First, define a Bean:

@Data
static class User {
    private Integer id;
    private String name;
}
String jsonArr = "[{\"id\":111,\"name\":\"test1\"},{\"id\":112,\"name\":\"test2\"}]";
JSONArray array = JSONUtil.parseArray(jsonArr);

List<User> userList = JSONUtil.toList(array, User.class);

// 111
userList.get(0).getId();

Converting to a List of Dicts

Dict is a special Map defined by Hutool that provides Map functionality with string keys and provides getXXX methods. The conversion is similar:

String jsonArr = "[{\"id\":111,\"name\":\"test1\"},{\"id\":112,\"name\":\"test2\"}]";
JSONArray array = JSONUtil.parseArray(jsonArr);

List<Dict> list = JSONUtil.toList(array, Dict.class);

// 111
list.get(0).getInt("id");

Converting to an Array

String jsonArr = "[{\"id\":111,\"name\":\"test1\"},{\"id\":112,\"name\":\"test2\"}]";
JSONArray array = JSONUtil.parseArray(jsonArr);

User[] list = array.toArray(new User[0]);

JSON Path

If the levels of JSON are particularly deep, getting a certain value can become very cumbersome and the code can become bloated. Hutool provides the getByPath method to obtain values in JSON using expressions.

String jsonStr = "[{\"id\": \"1\",\"name\": \"a\"},{\"id\": \"2\",\"name\": \"b\"}]";
final JSONArray jsonArray = JSONUtil.parseArray(jsonStr);

// b
jsonArray.getByPath("[1].name");