获取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);
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值