获取json中的key与value中的方法

  1. -----JS-------

  2. function getJson(key){  
  3.     var jsonObj={"name":"赵云","age":"24","profession":"武将"};  
  4.     //1、使用eval方法      
  5.     var eValue=eval('jsonObj.'+key);  
  6.     alert(eValue);  
  7.     //2、遍历Json串获取其属性  
  8.     for(var item in jsonObj){  
  9.         if(item==key){  //item 表示Json串中的属性,如'name'  
  10.             var jValue=jsonObj[item];//key所对应的value  
  11.             alert(jValue);  
  12.         }  
  13.     }  
  14.     //3、直接获取  
  15.     alert(jsonObj[''+key+'']);  
  16. }  
  17. ------- jquery-----------
  18. var json = [
        {"id":"1","pid":"0","tagName":"red"},
        {"id":"5","pid":"0","tagName":"green"}
    ];
     
    $.each(json, function(idx, obj) {
        alert(obj.tagName);
    });
  19. 假如出现如下报错 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}]
  20. 改为标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。
  21. $.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);

你可能感兴趣的:(获取json中的key与value中的方法)