如何将json字符串转换成数组对象
发布网友
发布时间:2022-04-25 16:17
我来回答
共1个回答
热心网友
时间:2023-10-16 16:22
将json字符串转成Java的Array数组
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 Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"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<Student> 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();
}
}