自己一个个循环判断虽然可以实现,但是工程量比较大,而且要是增加层次,就又得自己手动添加。。如果用递归的话。返回的类型不知道怎么去控制。求大佬抬一手。应该怎样返回合适的类型。达成map的嵌套存储
意思是,你有个JSON字符串,可能是无限子级的。你现在要转换为java对象 Map<…>
不知道怎么操作?
转成层级存储。。不知道怎么弄
没台明白想干嘛
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
class Bean {
private Integer id;
private String title;
private List<Bean> children;
@Override
public String toString() {
return "Bean [id=" + id + ", title=" + title + ", children=" + children + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Bean> getChildren() {
return children;
}
public void setChildren(List<Bean> children) {
this.children = children;
}
}
public class MainTest {
public static void main(String[] args) {
String json = "[{\"id\":22,\"title\":\"游客\",\"children\":[{\"id\":31,\"title\":\"8\",\"children\":[{\"id\":41,\"title\":\"18\"}]}]},{\"id\":33,\"title\":\"科皓\",\"children\":[{\"id\":34,\"title\":\"10\",\"children\":[{\"id\":42,\"title\":\"18\"},{\"id\":84,\"title\":\"15\"}]}]}]";
List<Bean> result = JSON.parseObject(json, new TypeReference<List<Bean>> () {});
System.out.println(JSON.toJSONString(result));
}
}
1 Like