fastJson对于json格式字符串的解析主要用到了一下三个类:

JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换。

JSONObject:fastJson提供的json对象。

JSONArray:fastJson提供json数组对象。

我们可以把JSONObject当成一个Map<String,Object>来看,只是JSONObject提供了更为丰富便捷的方法,方便我们对于对象属性的操作。我们看一下源码。

同样我们可以把JSONArray当做一个List<Object>,可以把JSONArray看成JSONObject对象的一个集合。

1.result格式一:

{
    "studentName":"true",
    "studentAge":"123" 
}
JSONObject jsonObject=JSON.parseObject(result);      //转换成object
jsonObject.getString("studentAge")    //获取object中studentAge字段;  
System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));                                                     

 2.格式二:

[
  {
     "studentName":"lily",
     "studentAge":12
  },
  {
     "studentName":"lucy",
     "studentAge":15
  }
]
JSONArray jsonArray = JSON.parseArray(result);
//JSONArray jsonArray1 = JSONArray.parseArray(result);//因为JSONArray继承了JSON,所以这样也是可以的

 //遍历方式1
 int size = jsonArray.size();
 for (int i = 0; i < size; i++){
    JSONObject jsonObject2 = jsonArray.getJSONObject(i);  
 System.out.println(jsonObject2.getString("studentName")+":"+jsonObject2.getInteger("studentAge"));
        }

 //遍历方式2
   for (Object obj : jsonArray) {
   JSONObject jsonObject2 = (JSONObject) obj;   
System.out.println(jsonObject2.getString("studentName")+":"+jsonObject2.getInteger("studentAge"));
   }

3.格式三:

{
    "success":"true",
    "data":{
        "shop_uid":"123"
    }
}
JSONObject shop_user =JSON.parseObject(result);  
System.out.println(JSON.parseObject(shop_user.getString("data")).getString("shop_uid"));

 4.格式四:

{
 "teacherName":"crystall",
 "teacherAge":27,
 "course":
    {
       "courseName":"english",
       "code":1270
    },
  "students":
    [
      {
         "studentName":"lily",
         "studentAge":12
      },
      {
         "studentName":"lucy",
         "studentAge":15
      }
   ]
}
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
 //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON,所以这样也是可以的
String teacherName = jsonObject.getString("teacherName");
Integer teacherAge = jsonObject.getInteger("teacherAge");
JSONObject course = jsonObject.getJSONObject("course");
JSONArray students = jsonObject.getJSONArray("students");
System.out.println(teacherName+","+teacherAge+","+course+","+students);

 

 

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:4 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐