FastJson解析字符串

一.需求:獲取Json字符串中的某個字段值

二.實現代碼

public class test {
    private static  String  COMPLEX_JSON_STR = "{\"status\":\"OK\",\"request_id\":\"159227615319652307143355\",\"result\":{\"searchtime\":0.064872,\"total\":1,\"num\":1,\"viewtotal\":1,\"compute_cost\":[{\"index_name\":\"VidService\",\"value\":0.29}],\"items\":[{\"fields\":{\"vid\":\"607247139647\",\"index_name\":\"VidService\"},\"property\":{},\"attribute\":{},\"variableValue\":{},\"sortExprValues\":[\"10000\"]}],\"facet\":[]},\"errors\":[],\"tracer\":\"\",\"ops_request_misc\":\"%7B%22request%5Fid%22%3A%22159227615319652307143355%22%2C%22scm%22%3A%221.120655746..%22%7D\"}";
    public static void main(String[] args) {
        JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray items = result.getJSONArray("items");
        for (int i = 0; i < items.size();i++){
            JSONObject item = items.getJSONObject(i);
            JSONObject fields = item.getJSONObject("fields");
            System.out.println(fields.get("vid"));
        }
    }
 }

三.知識點

  • JSONObject的數據是用 {  } 來表示的;
  • JSONArray由JSONObject構成的數組,用  [ { } , { } , ......  , { } ]  來表示的 ;
  • 區別:一個最外面用的是 {  }  ,一個最外面用的是 [  ];
  • 從JSONArray中獲得JSONObject對象:JSONObject   jsonObject  =  jsonArray.getJSONObject(i);
  • 獲取JSON裏面的數據:jsonObject.get( "id" ) ;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章