当前位置:网站首页>fastjson使用方法
fastjson使用方法
2022-07-29 11:28:00 【sword to coding】
本文主要介绍项目中经常使用到的json库fastjson,这是在前后端分离项目中最常使用到的json库
一.引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
二. 将一个java对象转化为JSON格式
### 在对象中对成员变量使用注解@JSONField
public class Person {
@JSONField(name = "AGE")
private int age;
@JSONField(name = "FULL NAME")
private String fullName;
@JSONField(name = "DATE OF BIRTH")
private Date dateOfBirth;
public Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName= fullName;
this.dateOfBirth = dateOfBirth;
}
// standard getters & setters
}
使用方法JSON.toJSONString()
private List<Person> listOfPersons = new ArrayList<Person>();
@Before
public void setUp() {
listOfPersons.add(new Person(15, "John Doe", new Date()));
listOfPersons.add(new Person(20, "Janette Doe", new Date()));
}
@Test
public void whenJavaList_thanConvertToJsonCorrect() {
String jsonOutput= JSON.toJSONString(listOfPersons);
}
结果
[
{
"AGE":15,
"DATE OF BIRTH":1468962431394,
"FULL NAME":"John Doe"
},
{
"AGE":20,
"DATE OF BIRTH":1468962431394,
"FULL NAME":"Janette Doe"
}
]
这里@JSONField(name = “AGE”) 其实就是将 返回的json键从成员变量的age转化为AGE,如果这里不填name,则默认为成员变量的名字。
我们在来看看注解@JSONField 的其他参数
@JSONField(name="AGE", serialize=false)
private int age;
@JSONField(name="LAST NAME", ordinal = 2)
private String lastName;
@JSONField(name="FIRST NAME", ordinal = 1)
private String firstName;
@JSONField(name="DATE OF BIRTH", format="dd/MM/yyyy", ordinal = 3)
private Date dateOfBirth;
- serialize 序列化标志,当为false的时候,该成员不作为json的键值
- ordinal 在json中的排序,=1的时候排第一个
- format 指定日期返回的格式
结果如下:
[
{
"FIRST NAME":"Doe",
"LAST NAME":"Jhon",
"DATE OF BIRTH":"19/07/2016"
},
{
"FIRST NAME":"Doe",
"LAST NAME":"Janette",
"DATE OF BIRTH":"19/07/2016"
}
]
FastJson还有一个BeanToArray序列化特性:
String jsonOutput= JSON.toJSONString(listOfPersons, SerializerFeature.BeanToArray);
[
[
15,
1469003271063,
"John Doe"
],
[
20,
1469003271063,
"Janette Doe"
]
]
更多关于SerializeFeature:SerializeFeature
三.创建一个Json对象
JSONObejct可以看作我们常用到的对象
JSONArray可以看作一个列表数组
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
输出
[
{
"AGE":"10",
"DATE OF BIRTH":"2016/12/12 12:12:12",
"FULL NAME":"Doe 0"
},
{
"AGE":"10",
"DATE OF BIRTH":"2016/12/12 12:12:12",
"FULL NAME":"Doe 1"
}
]
前面我们使用java最想转化成json,接下来我们看看如何将json字符串转化为java对象
四.将json字符串解析为java对象
JSON.parseObject()
测试用例:
@Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
结构:
Person [age=20, fullName=John Doe, dateOfBirth=Wed Jul 20 08:51:12 WEST 2016]
注意事项:
我们可以使用JSON.parseObject()从 JSON 字符串中获取 Java 对象。
请注意,如果您已经声明了自己的参数化构造函数,则必须定义无参数或默认构造函数,否则将抛出com.alibaba.fastjson.JSONException 。
忽略反向序列化
通过使用 @JSONField 注解中的选项反序列化,我们可以忽略特定字段的反序列化,在这种情况下,默认值将自动应用于被忽略的字段:
@JSONField(name = "DATE OF BIRTH", deserialize=false)
private Date dateOfBirth
//结果
Person [age=20, fullName=John Doe, dateOfBirth=null]
边栏推荐
- After connect and SQL join in on conditions and where
- On CompareTo method in string
- Hugo NexT V4 介绍
- 基于flask实现的mall商城---用户模块
- QT's user-defined interface (borderless and movable)
- What is kubernetes custom resource definition (CRD)?
- 多线程顺序运行的 4 种方法,面试随便问!
- 基本.分块
- 深入理解C# 可空类型
- LeetCode_ 416_ Divide equal sum subsets
猜你喜欢

Qt 之自定义界面(实现无边框、可移动)

如何在匹配行之前使用 grep 显示文件名和行号

Discussion on the application of arcing smart electricity in elderly care institutions

DNS protocol, ICMP protocol, NAT technology

Meituan and hungry were interviewed by Hangzhou supervisors to implement the responsibility of food safety management and prohibit malicious competition

How to use grep to find pattern matching across multiple lines

DOD and Dor, two artifacts to reduce "cognitive bias"

8. Interleave - understand ThreadPoolExecutor thread pool from architecture design to practice

7月3日文: 表面上有危险,实属安全周期,大概率会快速上扬的个股

Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29
随机推荐
基于flask实现的mall商城---用户模块
【图像处理】基于中轴变换实现图像骨架提取附matlab代码
正则表达式匹配网址
"100 Interview Knowledge Collections" 1. Interview Skills丨Do you really understand HR's careful thinking?
【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
北京大学公开课重磅来袭!欢迎走进「AI for Science」课堂
Deep understanding of c # delegate into the fast lanes
From scratch Blazor Server (3) - add cookie authorization
️ 炒 股 实 战丨原 地 起 飞 ️
HMS Core Discovery第16期回顾|与虎墩一起,玩转AI新“声”态
Spark高效数据分析01、idea开发环境搭建
Drawing box and ellipse of WPF screenshot control (IV) "imitating wechat"
解决idea在debug模式下变得非常慢的问题
AI model risk assessment Part 2: core content
Flink UDF 函数汇总
Learning with Recoverable Forgetting阅读心得
8. Interleave - understand ThreadPoolExecutor thread pool from architecture design to practice
Zhou Hongyi: 360 is the largest secure big data company in the world
It is recommended to collect a thousand ways to write sql row to column!!
Matplotlib Chinese question