如下一个json数组:
{
"feature":"fresh_today",
"photos":[
{
"id":"5",
"name":"Dandelion5"
},
{
"id":"3",
"name":"Dandelion3"
}
]
}
怎样做到,知道了photo中的id为5,取出{ "id":"5","name":"Dandelion5" }中的name的值?
使用遍历吗?
自己写的一个办法,不知道,是否合适。。。
public static void main(String[] args) {
TestJson test=new TestJson();
test.getValue();
}
public void getValue(){
String str = "{\"data\":[{\"id\":\"1\",\"name\":\"name1\"}," +
"{\"id\":\"2\",\"name\":\"name2\"},{\"id\":\"3\",\"name\":\"name3\"},]}";
//
JSONObject jsonObject = JSONObject.fromObject(str);
JSONArray result = jsonObject.getJSONArray("data");
//System.out.println(result);
for (int i = 0; i < result.size(); i++) {
//System.out.println(result);
String id = result.getJSONObject(i).getString("id");
System.out.println(id);
if(id.equals("2")){
System.out.println(id);
System.out.println(i);
String name = result.getJSONObject(i).getString("name");
System.out.println(name);
}
}
}
是java的话基本就是new一个对象 然后id=5的时候 对象等于当前的这个json 然后就简单了
遍历photos的数组。然后一个个比较id,当是5的时候。读取name的key
json遍历直接取值
用scriptenginner
遍历"photos",当id=5,时的值
用gson把json转化为一个map对象,然后map.get("photo"),然后再把这个object转化为map然后就可以get id了
$(function() {
for(var i = 0; i<data.photos.length; i++){
if(data.photos[i].id=="5"){
console.log(data.photos[i].name);
}
}
})