怎么把页面传过来的JSON数组转换成list

高分请讲解下,怎么把页面传过来的JSON数组转换成list
最新回答
很酷的小当家

2025-03-30 02:52:43

在Java中,我们可以将JSON字符串转换为数组或列表,以便于进一步处理。假设我们有一个JSON字符串,内容如下:

{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}

如果要将这个JSON字符串转换为Java数组,可以先将其包装成一个数组形式,然后再进行转换。代码如下:

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
@Test
public void readJSON2Array() {
try {
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
Object[] os = jsonArray.toArray();
System.out.println(os.length);
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
System.out.println(stus.length);
System.out.println(stus[0]);
} catch (Exception e) {
e.printStackTrace();
}
}

运行结果:

JSON Array String >>> Java Array

1

{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}

1

接下来,如果要将JSON字符串转换为Java的List集合,可以使用类似的方法。代码如下:

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
public void readJSON2List() {
try {
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
List list = JSONArray.toList(jsonArray, Student.class);
System.out.println(list.size());
System.out.println(list.get(0));
list = JSONArray.toList(jsonArray);
System.out.println(list.size());
System.out.println(list.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}

运行结果:

JSON Array String >>> Java List

1

{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}

1