原本的业务需要就是在获得了多级菜单的数据之后,需要遍历每一项进行新属性塞入
原报文格式:
{
"list":[
{
"id":"1",
"parentid":"0",
"children":[
{
"id":"3",
"parentid":"1",
"children":[
{
"id":"4",
"parentid":"3"
}
]
}
]
},
{
"id":"2",
"parentid":"0"
}
]
}
遍历转换之后的报文:
{
"list":[
{
"new":"我是新的啊",
"children":[
{
"new":"我是新的啊",
"children":[
{
"new":"我是新的啊",
"id":"4",
"parentid":"3"
}
],
"id":"3",
"parentid":"1"
}
],
"id":"1",
"parentid":"0"
},
{
"new":"我是新的啊",
"id":"2",
"parentid":"0"
}
]
}
全部代码:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class test {
public static void main(String[] args) {
String str = "{\n" +
" \"list\":[\n" +
" {\n" +
" \"id\":\"1\",\n" +
" \"parentid\":\"0\",\n" +
" \"children\":[\n" +
" {\n" +
" \"id\":\"3\",\n" +
" \"parentid\":\"1\",\n" +
" \"children\":[\n" +
" {\n" +
" \"id\":\"4\",\n" +
" \"parentid\":\"3\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"id\":\"2\",\n" +
" \"parentid\":\"0\"\n" +
" }\n" +
" ]\n" +
"}";
JSONObject obj = JSON.parseObject(str);
changArray(obj.getJSONArray("list"));
System.out.println(obj.toJSONString());
}
public static JSONArray changArray(JSONArray objarray ){
for (int i = 0; i < objarray.size(); i++) {
objarray.getJSONObject(i).put("new","我是新的啊");
Object o = objarray.getJSONObject(i).get("children");
if(o != null){
changArray(objarray.getJSONObject(i).getJSONArray("children"));
}
}
return objarray;
}
}