原生JS方法
function getJson(key){
var jsonObj={"name":"赵云","age":"24","profession":"武将"};
//1、使用eval方法
var eValue=eval('jsonObj.'+key);
alert(eValue);
//2、遍历Json串获取其属性
for(var item in jsonObj){
if(item==key){ //item 表示Json串中的属性,如'name'
var jValue=jsonObj[item];//key所对应的value
alert(jValue);
}
}
//3、直接获取
alert(jsonObj[''+key+'']);
//alert(jsonObj['name']);
}
使用JQuery
var json = [
{"id":"1","pid":"0","tagName":"red"},
{"id":"5","pid":"0","tagName":"green"}
];
$.each(json, function(idx, obj) {
alert(obj.tagName);
});
如果出现如下报错
Uncaught TypeError: Cannot use 'in' operator to search for '375' in [{"id":"01","state":null,"pid":"0","icon":null,"iconClose":null,"iconOpen":null,"name":"oos??","open":true,"isParent":true}]
改为标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。
$.each(JSON.parse(json), function(idx, obj) {
alert(obj.tagName);
});
java语法
import net.sf.json.JSONObject;
import com.google.gson.Gson;
import com.nenglong.k12.oos.module.po.resource.Exercise;
String res = "{"_index":"k12oos","_type":"exercise","_id":"-0WtGG1FhQSmqIQhKU8pMg","_version":2,"found":true,"_source":{"code":"1009430255","stageId":"go2Leq1wj5y8vuA_5w7Azw","gradeId":"26vYkWDVjhivNno6Kbz7ZM","courseStageId":"PcjbvAQ8h9KaTfZ8q6UZcw","exerciseType":{"name":"张三","id":"-0WtGG1FhQSmqIQhKU8pMg"}}";
JSONObject jsonObject = new JSONObject();
jsonObject = jsonObject.fromObject(res);//将String转为JSON数据
String exerciseStr = jsonObject.getString("_source");//获取key为"_source"的值。
Gson gson = new Gson();
Exercise exercise = gson.fromJson(exerciseStr, Exercise.class);
必须 注册 为本站用户, 登录 后才可以发表评论!