com.alibaba.fastjson使用总结

json的解析最主要的工作就是,javaBean对象,json对象,json格式字符串之间的相互转换

最常用:​​​​​​​

// json字符串-> javabean
Student student = JSONObject.parseObject(JSON_OBJ_STR, Student.class);
List<Student> studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);

// javabean -> json字符串
String jsonString = JSONObject.toJSONString(student);
List<Student> students = new ArrayList<Student>();
String jsonString = JSONArray.toJSONString(students);

参考博客:写的比较全面,简单易懂

高性能JSON框架之FastJson的简单使用 - SegmentFault 思否

注意:

json格式字符串需要满足:

String mediaList = "[{\"mediaId\":11,\"mediaName\":\"abc\"},{\"mediaId\":12,\"mediaName\":\"abc2\"}]";

1.mediaId、mediaName可以不用""引号;但是其对应的值(如上的abc,abc2)如果是字符串,必须需要""用引号;

  1. JSON格式字符串   ←→JSONObject对象

  • JSON格式字符串 →JSONObject对象  
JSONObject jsonObject =JSONObject.parseObject((JSON_OBJ_STR);

JSONArray jsonArray =JSONArray.parseArray(JSON_ARRAY_STR);
    for (Object object : jsonArraystudents) {
        JSONObject jsonObjectone = (JSONObject) object;
    }
  • JSONObject对象 →JSON格式字符串
    // 第一种方式
    String jsonString = JSONObject.toJSONString(jsonObject);

    // 第二种方式
    String jsonString = jsonObject.toJSONString();

     2. JSON格式字符串   ←→javaBean对象

  • JSON格式字符串   →javaBean对
//第一种方式
    JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
    String studentName = jsonObject.getString("studentName");
    Integer studentAge = jsonObject.getInteger("studentAge");
    Student student = new Student(studentName, studentAge);

    List<Student> students = new ArrayList<Student>();
    Student student = null;
    for (Object object : jsonArray) {
        JSONObject jsonObjectone = (JSONObject) object;
        String studentName = jsonObjectone.getString("studentName");
        Integer studentAge = jsonObjectone.getInteger("studentAge");
        student = new Student(studentName,studentAge);
        students.add(student);
    }

//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
    Student student = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>();

    List<Student> studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});
   

//第三种方式,使用Gson的思想
    Student student = JSONObject.parseObject(JSON_OBJ_STR, Student.class);

    List<Student> studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
    
  •   javaBean对象 →JSON格式字符串
    String jsonString = JSONObject.toJSONString(student);
    
    List<Student> students = new ArrayList<Student>();
    String jsonString = JSONArray.toJSONString(students);

    3.JSONObject对象   ←→javaBean对象(以JSON字符串为媒介)

  • javaBean对象→JSONObject对象
        //方式一
        String jsonString = JSONObject.toJSONString(student);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
    
        String jsonString = JSONArray.toJSONString(students);
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
    
    
        //方式二
        JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(student);
    
        JSONArray jsonArray1 = (JSONArray) JSONArray.toJSON(students);
  • JSONObject→javaBean对象
        //第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        Student student = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Student>() {});
       
        ArrayList<Student> students = JSONArray.parseObject(jsonArray.toJSONString(),
                new TypeReference<ArrayList<Student>>() {});
    
    
        //第二种方式,使用Gson的思想
        Student student1 = JSONObject.parseObject(jsonObject.toJSONString(), Student.class);
       
        List<Student> students1 = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);
    

另外还有以下两个成员方法用的比较多:

JSONObject jsonObjectcourse = jsonObject.getJSONObject("course");

JSONArray jsonArraystudents = jsonObject.getJSONArray("students");

public void testComplexJSONStrToJSONObject() {

    JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

    String teacherName = jsonObject.getString("teacherName");
    Integer teacherAge = jsonObject.getInteger("teacherAge");

    System.out.println("teacherName:  " + teacherName + "   teacherAge:  " + teacherAge);

    JSONObject jsonObjectcourse = jsonObject.getJSONObject("course");
     //获取JSONObject中的数据
    String courseName = jsonObjectcourse.getString("courseName");
    Integer code = jsonObjectcourse.getInteger("code");

    System.out.println("courseName:  " + courseName + "   code:  " + code);

    JSONArray jsonArraystudents = jsonObject.getJSONArray("students");

    //遍历JSONArray
    for (Object object : jsonArraystudents) {

        JSONObject jsonObjectone = (JSONObject) object;
        String studentName = jsonObjectone.getString("studentName");
        Integer studentAge = jsonObjectone.getInteger("studentAge");

        System.out.println("studentName:  " + studentName + "   studentAge:  " + studentAge);
    }
}
### 使用 `@JSONField` 注解定制序列化与反序列化行为 #### 1. 更改字段名称 通过 `@JSONField(name = "custom_name")`,可以指定 JSON 数据中某个字段的名称与其 Java 属性名称不同。这在实际开发中非常常见,尤其是在对接外部接口时需要遵循特定命名规则的情况。 ```java import com.alibaba.fastjson.annotation.JSONField; public class User { private int id; @JSONField(name = "user_name") private String name; private int age; // 构造函数、getter 和 setter 方法省略 } ``` 上述代码会将 `name` 字段映射为 JSON 中的 `"user_name"` 键[^3]。 --- #### 2. 控制字段忽略 如果希望某些字段不参与序列化或反序列化操作,可以通过 `serialize = false` 或 `deserialize = false` 来实现。 ```java public class User { private int id; @JSONField(serialize = false) private String password; private int age; // 构造函数、getter 和 setter 方法省略 } ``` 在此例子中,`password` 字段不会被序列化到 JSON 结果中。 --- #### 3. 设置时间格式 对于日期类型的字段,默认情况下可能无法满足业务需求的时间格式。此时可通过 `format` 参数来指定所需的日期格式。 ```java import java.util.Date; public class Event { private String title; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date eventDate; // 构造函数、getter 和 setter 方法省略 } ``` 此配置会使 `eventDate` 被序列化为指定的字符串格式。 --- #### 4. 处理多名称兼容性 当存在多个可能的键名时,可使用 `alternateNames` 参数支持旧版或备用名称解析。 ```java public class Order { @JSONField(name = "order_id", alternateNames = {"orderId"}) private String orderId; // 构造函数、getter 和 setter 方法省略 } ``` 这样,在反序列化过程中既接受 `"order_id"` 又能识别 `"orderId"` 的输入[^5]。 --- #### 5. 延迟加载优化 为了提高性能并减少不必要的计算开销,可以利用 `ordinal = true` 实现延迟加载功能。 ```java public class Product { private String productId; @JSONField(ordinal = 10) private double price; // 构造函数、getter 和 setter 方法省略 } ``` 这里的 `price` 将按照其优先级顺序进行处理。 --- #### 总结 以上展示了如何借助 `@JSONField` 注解完成多种场景下的自定义序列化与反序列化逻辑调整。无论是重命名字段还是管理复杂的数据结构变换,该工具都提供了极大的灵活性和支持能力。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值