java实现树形结构,可以把String[] a = {"1", "1-3-4", "1-2", "1-2"}这个数组,转变成如图的树json么? 20
2个回答
展开全部
//先定义一个类,方便转换
public class Menu {
private Long id;
private List child = new ArrayList<>();
public Menu(Long id) {
this.id = id;
}
}
public class String2JsonTest {
public static void main(String[] args) {
String[] a = {"1", "1-3-2", "1-2", "1-2"};
List list2 = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("-");
List tempList = list2;
Menu tempMenu = null;
for (int j = 0; j < b.length; j++) {
tempMenu = new Menu(Long.valueOf(b[j]));
Menu exist = isExist(tempMenu,tempList);
if(exist==null){
tempList.add(tempMenu);
tempList = tempMenu.getChild();
}else{
tempList = exist.getChild();
}
}
}
String jsonArray2 = JSONArray.toJSONString(list2);
System.out.println(jsonArray2);
}
private static Menu isExist(Menu menu,List<Menu> list){
for (Menu obj : list) {
if(menu.getId().equals(obj.getId())){
return obj;
}
}
return null;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询