这是JSONObject { "status": 200, "data": [{ "id": "a5829f94-52dd-425d-8fe6-249804dd0190", "name": "分析案例", "createBy": "Anna", "packs": [] }, { "id": "d6d307e8-7d56-4ce8-9325-b480e7e1d9ef", "name": "图表", "createBy": "admin", "packs": [{ "id": "0fde3866015547e19edb292ecc1182b6", "name": "文件夹", "createBy": "admin", "packs": [] }] } ] } 这是一个树形结构用Java实现,获取data并将数据转换成List<UserPack> UserPack的属性包括: String id; String nam; String createBy; List<UserPack> packs;
时间: 2023-07-30 07:12:28 浏览: 102
使用JSONObject解析json数据
你可以使用以下代码将给定的JSON数据转换为List<UserPack>:
```java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String json = "{\n" +
"\"status\": 200,\n" +
"\"data\": [{\n" +
"\"id\": \"a5829f94-52dd-425d-8fe6-249804dd0190\",\n" +
"\"name\": \"分析案例\",\n" +
"\"createBy\": \"Anna\",\n" +
"\"packs\": []\n" +
"},\n" +
"{\n" +
"\"id\": \"d6d307e8-7d56-4ce8-9325-b480e7e1d9ef\",\n" +
"\"name\": \"图表\",\n" +
"\"createBy\": \"admin\",\n" +
"\"packs\": [{\n" +
"\"id\": \"0fde3866015547e19edb292ecc1182b6\",\n" +
"\"name\": \"文件夹\",\n" +
"\"createBy\": \"admin\",\n" +
"\"packs\": []\n" +
"}]\n" +
"}\n" +
"]\n" +
"}";
List<UserPack> userPacks = convertJSONToList(json);
for (UserPack userPack : userPacks) {
System.out.println("UserPack ID: " + userPack.getId());
System.out.println("UserPack Name: " + userPack.getName());
System.out.println("UserPack Created By: " + userPack.getCreateBy());
System.out.println("UserPack Packs: " + userPack.getPacks());
System.out.println();
}
}
public static List<UserPack> convertJSONToList(String json) {
List<UserPack> userPacks = new ArrayList<>();
JSONObject jsonObject = JSONObject.parseObject(json);
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.size(); i++) {
JSONObject userPackObject = dataArray.getJSONObject(i);
UserPack userPack = new UserPack();
userPack.setId(userPackObject.getString("id"));
userPack.setName(userPackObject.getString("name"));
userPack.setCreateBy(userPackObject.getString("createBy"));
JSONArray packsArray = userPackObject.getJSONArray("packs");
if (packsArray != null && packsArray.size() > 0) {
userPack.setPacks(convertJSONToList(packsArray.toJSONString()));
}
userPacks.add(userPack);
}
return userPacks;
}
}
class UserPack {
private String id;
private String name;
private String createBy;
private List<UserPack> packs;
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public List<UserPack> getPacks() {
return packs;
}
public void setPacks(List<UserPack> packs) {
this.packs = packs;
}
}
```
这段代码使用了FastJSON库来解析JSON并将其转换为List<UserPack>。你可以根据需要修改UserPack类的属性和方法。
阅读全文