獲取Json字符串中的key和value

獲取Json字符串中的key和valuejava

在web項目中常常會用到json數據(如:struts2處理請求返回json數據給jsp解析),所以,JSONObject對象是必備的,這時就須要引入相關的jar包了。web

json所須要的jar包以下:json

json-lib-2.3-jdk15.jar

json所依賴的jar以下: jsp

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實現代碼:google

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);
相關文章
相關標籤/搜索