FastJson解析数据技巧

        FastJson是用于java后台处理json格式数据的一个工具包,包括“序列化”和“反序列化”两部分,具有速度快、功能强、无依赖等特点。

fastjson解析json主要用到如下三个类:

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

2、JSONObject:fastJson提供的json对象。

3、JSONArray:fastJson提供json数组对象。

使用场景1:

实体Student

public class Student{

  private int id;

  private String name;   

}

解析

publicstaticvoid main(String[] args){

    String json= “{“id”:1,”name”,”humorboy”}”;

    JSONObject student = JSONObject.parseObject(json);

   Student student= JSON.toJavaObject(student,Student.class);

}

使用场景2

(1)   解析一般json字符串

private static final String json_str= “{\”studentName\”:\”lily\”,\”studentAge\”:12}”;

JSONObject  jsonObject = JSON.parseObject(json_str);

 //JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的        System.out.println(jsonObject.getString(“studentName”)+”:”+jsonObject.getInteger(“studentAge”));

(2) 解析 json字符串-数组类型

private static final String json_array = “[{\”studentName\”:\”lily\”,\”studentAge\”:12},{\”studentName\”:\”lucy\”,\”studentAge\”:15}]”;

JSONArray jsonArray = JSON.parseArray(json_array );

//JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的

 // 遍历方式1

int size = jsonArray.size();

        for(inti = 0; i < size; i++){

            JSONObject jsonObject = jsonArray.getJSONObject(i)                                     System.out.println(jsonObject.getString(“studentName”)+”:”+jsonObject.getInteger(“studentAge”));

        }

        // 遍历方式2

    for (Object obj : jsonArray) {

            JSONObject jsonObject = (JSONObject) obj;                        System.out.println(jsonObject.getString(“studentName”)+”:”+jsonObject.getInteger(“studentAge”));

        }

(3)  解析复杂格式json字符串

private static final String complex_json_str = “{\”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”);

    原文作者:寒江楓雨
    原文地址: https://www.jianshu.com/p/fb35dbf6b601
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞