样例数据:var jsonData = [{"id":"1","pid":"0","name":"家用电器"}, {"id":"4","pid":"1","name":"大家电"}, {"id":"5","pid":"1","name":"生活电器"}, {"id":"2","pid":"0","name":"服饰"}, {"id":"3","pid":"0","name":"化妆"}, {"id":"7","pid":"4","name":"空调"}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣机"}, {"id":"10","pid":"4","name":"热水器"}, {"id":"11","pid":"3","name":"面部护理"}, {"id":"12","pid":"3","name":"口腔护理"}, {"id":"13","pid":"2","name":"男装"}, {"id":"14","pid":"2","name":"女装"}, {"id":"15","pid":"7","name":"海尔空调"}, {"id":"16","pid":"7","name":"美的空调"}, {"id":"19","pid":"5","name":"加湿器"}, {"id":"20","pid":"5","name":"电熨斗"}]
2、实现方法:
function creatTreeData(list){
var clonelist = JSON.parse(JSON.stringify(list))
var result =clonelist.filter(function(father){
var childlist = clonelist.filter(function(child){
return father.id= child.pid
})
if(childlist.length>0){
father.children=childlist
}
return father.pid ==0
})
return result
}
3、方法封装
function treeData(list,id,pid,children){
var clone = JSON.parse(JSON.stringify(list))
return clone.filter(function(father){
var childlist =clone.filter(function(child){
return father[id]==child[pid]
})
if(childlist.length>0){
father[children]=childlist
}
return father[pid]==0
})
}
1.List list = new ArrayList。
2.list.add(测试1)。
3.list.add(测试2)。
4.list.add(测试3)。
5.JSONArray jsonArray JSONArray.fromObject(list)。
6.System.out.println(jsonArray.toString。
7.这边要导包需要jsonlib.jarnet.sf.json.JSONArray。
用java初始化一个list,向list中添加值,并输出list中的值:
1.import java.util.
2.public class .
3. public static void main(String arg[]) .
4. List lis = new Arraylist.
5. lis.add("wo").
6. lis.add("shi").
7. lis.add("wang").
8.for(int i=0i<lis.size()i++).
9. System.out.print(lis.get(i)+"").
例如:JSON字符串:
var str1 = '{ "name": "cxh", "sex": "man" }'
JSON对象:
var str2 = { "name": "cxh", "sex": "man" }
一、JSON字符串转换为JSON对象
要使用上面的str1,必须使用下面的方法先转化为JSON对象:
//由JSON字符串转换为JSON对象
var obj = eval('(' + str + ')')
或者
var obj = str.parseJSON()//由JSON字符串转换为JSON对象
或者
var obj = JSON.parse(str)//由JSON字符串转换为JSON对象
然后,就可以这样读取:
Alert(obj.name)
Alert(obj.sex)
特别注意:如果obj本来就是一个JSON对象,那么使用eval()函数转换后(哪怕是多次转换)还是JSON对象,但是使用parseJSON()函数处理后会有问题(抛出语法异常)。