获取Json字符串中的key和value
在web项目中经常会用到json数据(如:struts2处理请求返回json数据给jsp解析),因此,JSONObject对象是必备的,这时就需要引入相关的jar包了。
json所需要的jar包如下:
json-lib-2.3-jdk15.jar
json所依赖的jar如下:
commons-beanutils-1.8.0.jar commons-collections-3.2.1.jar commons-lang-2.4.jar commons-logging-1.1.jar ezmorph-1.0.6.jar
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);
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16829.html