当前位置:网站首页>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]
边栏推荐
- TCP and UDP
- 暑假集训week1
- Pyqt5 rapid development and practice 6.6 qformlayout & 6.7 nested layout & 6.8 qsplitter
- Spark高效数据分析01、idea开发环境搭建
- Spark efficient data analysis 01. Establishment of idea development environment
- 2022最新 wifi大师小程序独立版3.0.8
- Insights into the development of the enterprise live broadcast industry in 2022
- Similarities and differences of QWidget, qdialog and qmainwindow
- Learning with Recoverable Forgetting阅读心得
- PyQt5快速开发与实战 6.6 QFormLayout(表单布局) && 6.7 嵌套布局 && 6.8 QSplitter
猜你喜欢

Drawing box and ellipse of WPF screenshot control (IV) "imitating wechat"

如何使用“COPY –link”加速 Docker 构建和优化缓存

Analysis of QT basic engineering

如何使用 grep 跨多行查找模式匹配

Basic construction of QT project

The 2022 open atom global open source summit opened in Beijing

2022年企业直播行业发展洞察

ECCV 2022 | ssp: a new idea of small sample tasks with self-supporting matching

The heavy | open atomic school source activity was officially launched

【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
随机推荐
学习周刊-总第64期-一个v2ex风格的开源论坛程序
SkiaSharp of WPF custom painting to bounce ball (case)
The 2022 open atom global open source summit opened in Beijing
Pyqt5 rapid development and practice 6.6 qformlayout & 6.7 nested layout & 6.8 qsplitter
Paddlelite compilation and code running through the disk
精通音视频开发是真的可以为所欲为
LeetCode_ 416_ Divide equal sum subsets
8. Interleave - understand ThreadPoolExecutor thread pool from architecture design to practice
Function comparison between report control FastReport and stimulus soft
迁徙数据平台简单介绍
INVALID_ARGUMENT : Invalid rank for input: modelInput Got: 3 Expected: 4 Please fix either the input
『面试知识集锦100篇』1.面试技巧篇丨HR的小心思,你真的懂吗?
matplotlib中文问题
[SwiftUI 开发] @State @Binding @ObservedObject @EnvironmentObject
Leetcode bit operation
TCP and UDP
Lucky draw system with background source code
判断两个对象的值是否都相等
Gbase8s core data backup
Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29