当前位置:网站首页>Use jackson to parse json data in detail
Use jackson to parse json data in detail
2022-08-11 03:51:00 【small double】
Java操作json数据
json 简介
概念
JSON:JavaScript Object Notations,即javaScript的对象表示法,是javaScript语法的一个子集,相当于javaScript中的一个对象.虽然json起源于javaScript,但是很多语言都支持jsonData format parsing and generation,是一种文本数据格式,官方的MIME类型是:application/json.
应用场景
- Commonly usedjavaScript,java,node.js开发的web应用中.
- 由于jsonSaved text data,So also used in someNoSqltype in the database based on the document type,例如MongoDB.
JSON与XMLLighter than that,更易于解析,数据传输更快 .
语法格式
就如前面说的json是javaScript的一个子集,Its manifestation is onejavaThe curly braces data object,同时jsonThe data format has strict syntax requirements,If there is a problem, the parsing will fail.其语法规则如下:
json中的数据是以键值对的形式存在的,There are the following requirements for key-value pairs:
- Both keys and values need to be enclosed in double quotes,Also the key must be a string,Values can be variousjavascript类型,Or something elsejson对象
- Separate key-value pairs with commas,But be careful not to use a comma in the last key-value pair,不然会报错
- 一个jsonObjects need to be enclosed in curly braces
- Values that are arrays need to be enclosed in square brackets
json值的类型:
- 字符串String
- 数字Number
- 对象Json
- 数组Array
- 布尔类型boolean
- null
不能为javaScript中undefined,函数,日期类型.
举例
person = {
"name":"zhangsan",
"age":21,
"girlFriend":{
"name":"lisi", "age":20},
"hobbies":["跑步", "篮球", "play game"],
"single":false
}
Sometimes we request from the networkjsonFormatted data is not so neat,这个时候就可以使用json在线解析工具了,将jsonCopy the string to view the specific outline of the data.
注意jsonAnnotations are not allowed in the data,To annotate, some other operations are required,The specific reasons can be found online.
json字符串
即是将json对象最 The outer curly braces are enclosed in double quotes,在数据传输过程中,Data is often transformed into json字符串,Then parse into json对象.例如
String person = "{
"name":"zhangsan",
"age":21,
"girlFriend":{
"name":"lisi", "age":20},
"hobbies":["跑步", "篮球", "play game"],
"single":false
}";
javaScript中读取数据
- json对象.键名 – person.name = “zhangsan”
- json对象[“键名”] – person[“age”] = 21
- json对象.数组对象[索引] – person.hobbies[2] = “play game”
- You can use the above for nested use – person.girlFriend.name = “lisi”
java操作json数据
jsonData formats can be usedwebThe front-end and back-end data transmission of the application is in progress,For example, the front end sendsajax请求数据.当使用javaAs a backend development language,corresponding analysis is required,生成jsonData tools,Below is a concise one,快速的json解析工具类:jackson.
jackson可以通过反序列化将前端传递的json对象转成一个java的对象(Usually a custom class instance),也可以将java对象序列化成json对象,Passed to the front-end page to be received.
- 序列化:将javaThe process of converting an object into byte stream data,
- 反序列化:Convert byte stream data to java对象的过程,
注意:jsonAlthough it is a text data format,However, in the process of network transmission, it still needs to be converted into byte stream data for transmission.
下面是jackson的使用
2.1导入jar包或依赖
导入jar包
与jackson有关的jar共有三个,分别是:
- jackson-annotations.jar – 下载地址:https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
- jackson-core.jar – 下载地址:https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
- jackson-databind – 下载地址:https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
into the corresponding address,Click on any version number and then click“查看全部”(中文网页),或者“view all”(英文网页),之后界面如下:
其他两个jarThe download of the package is the same.
maven工程中导入
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
由于在导入jackson-databind依赖时,The other two dependencies are also imported at the same time,So in project import only importjackson-databindDependency works too.
2.2 java对象转换成json字符串
jacksonused to sequence and de-sequencejson数据的类是ObjectMapper(对象映射);在包:com.fasterxml.jackson.databind中.下面举例说明ObjectMapper对象的使用:Assuming it has already been createdPerson的domain对象
1.将javaobject into onejson格式的字符串
public void test() {
Person p = new Person();
p.setName("张三");
p.setAge(21);
ObjectMapper mapper = new ObjectMapper(); //Create the object directly to call the relevant method
String json = mapper.writeValueAsString(p); //即可将p对象转化为json格式的字符串 -- "{"name":"张三", "age":21}"
}
writeValueAsString(Object obj): 可以将一个domainobject into the correspondingjson字符串,如果domainThere are properties with no value,则会用null替代.很常用!
List集合和Map对象都可以使用该方法,ListCollections are transformed into an array of nested objects in the format,MapObjects are transformed and useddomianThe format of the converted object is the same.
2.将java对象转化成jsonstring and write to the target source
- writeValue(File file, Objcet obj); – 将objThe contents of the object are writtenFile文件中
- writeValue(Writer writer, Object obj); – 将obj对象写入到Writer character stream object
- writeValue(OutputStream output, Object obj); – 将obj对象写入OutputStream in the byte stream object
public void test() {
Person p = new Person();
p.setName("张三");
p.setAge(21);
ObjectMapper mapper = new ObjectMapper(); //Create the object directly to call the relevant method
mapper.writeValue(new File("D://test.txt"), p); //将p对象写入File对象
mapper.writeValue(new FileWrite("D://test1.txt"), p);
mapper.writeValue(new FileOutputStream(new File("D://test2.txt")), p);
}
2.3 jackson相关的注解
- mentioned abovejava对象转化成ObjectMapper对象时,If the associated property has no value it will be converted to null,If we don't need related properties,You can add the following comment above the statement that defines the property:
@JsonIgnore
例如:
@JsonIgnore
private int money;
This is transforming into jsonWhen a string object is used, the property will not be converted.
Conversion of time attributes,可以使用下面注解
@JsonFormat(pattern = “yyyy-MM-dd”)
private Date birthday;
This is how the time format displayed is:2020-09-30,If you do not use the above annotations,Displays the timestamp of the corresponding time.
2.4 json转化为java对象
通过ObjectMapper方法将json字符串转化为java的domainObjects are also OK,But not used much,具体使用方式如下:
public void test() {
ObjectMapper mapper = new ObjectMapper(); //Create the object directly to call the relevant method
String json = "{"name":"张三", "age":21}";
Person person = mapper.readValue(json, Person.class); //可将json字符串转化为Person对象
}
This method is not so commonly used.
An example of front-end and back-end data interaction
模拟用户登录,Check whether the username and password entered by the user match,验证码是否正确,If there is an error, the corresponding prompt message will be returned,其中ResultInfo对象是一个domian对象,Used to save the corresponding error information.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
ResultInfo info = new ResultInfo();
ObjectMapper mapper = new ObjectMapper(); //创建ObjectMapper对象
//获取验证码
HttpSession session = request.getSession();
String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");
String checkcode = request.getParameter("check");
if (!checkcode.equalsIgnoreCase(checkcode_server)) {
info.setFlag(false);
info.setErrorMsg("验证码错误");
String json = mapper.writeValueAsString(info); //将对象转化成json字符串
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json); //Write the object to the front end
return ;
} else {
User user = new User();
try {
BeanUtils.populate(user, map);
//Keep user information insession中
session.setAttribute("user", user);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserService service = new UserServiceImpl();
boolean status = service.login(user);
if (status) {
if (!service.hasCertification(user)) {
info.setFlag(false);
info.setErrorMsg("Email has not been verified yet,Please check your email for verification!");
} else {
info.setFlag(true);
}
} else {
info.setFlag(false);
info.setErrorMsg("账号或密码错误");
}
String json = mapper.writeValueAsString(info); //将对象转化成json字符串
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json); //Write the object to the front end
}
}
ResultInfo类:
package cn.itcast.travel.domain;
import java.io.Serializable;
import java.util.Objects;
/** * 1.用于封装后端返回前端数据对象 * 2.At the same time, it is judged whether the returned data is wrong * 3.Record the information that the exception occurred -- Note that this is the error message used to display to the foreground */
public class ResultInfo implements Serializable {
/** * true: The backend returns normal results * false:The backend returned the wrong result */
private boolean flag;
/** * The backend returns the result data object */
private Object data;
/** * An exception error message occurred */
private String errorMsg;
public ResultInfo() {
}
/** * 带参构造 * @param flag */
public ResultInfo(boolean flag) {
this.flag = flag;
}
/** * 有参构造方法 * @param flag * @param errorMsg */
public ResultInfo(boolean flag, String errorMsg) {
this.flag = flag;
this.errorMsg = errorMsg;
}
/** * 有参构造方法 * @param flag * @param data * @param errorMsg */
public ResultInfo(boolean flag, Object data, String errorMsg) {
this.flag = flag;
this.data = data;
this.errorMsg = errorMsg;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
边栏推荐
- 浅析一下期货程序化交易好还是手工单好?
- [ADI low-power 2k code] Based on ADuCM4050, ADXL363, TMP75 acceleration, temperature detection and serial port printing, buzzer playing music (lone warrior)
- Interchangeability Measurements and Techniques - Calculation of Deviations and Tolerances, Drawing of Tolerance Charts, Selection of Fits and Tolerance Classes
- Get the length of the linked list
- What has programmatic trading changed?
- Build Zabbix Kubernetes cluster monitoring platform
- 【FPGA】day22-SPI协议回环
- MYSQLg advanced ------ return table
- 2022-08-10 The sixth group Hiding spring study notes
- 80端口和443端口是什么?有什么区别?
猜你喜欢
Binary tree related code questions [more complete] C language
console.log alternatives you didn't know about
A simple JVM tuning, learn to write it on your resume
What should I do if the channel ServerID is incorrect when EasyCVR is connected to a Hikvision Dahua device and selects another cluster server?
作业8.10 TFTP协议 下载功能
【FPGA】day21- moving average filter
【愚公系列】2022年08月 Go教学课程 035-接口和继承和转换与空接口
Description of ESB product development steps under cloud platform
【FPGA】day18-ds18b20实现温度采集
Interchangeability and Measurement Technology—Surface Roughness Selection and Marking Method
随机推荐
【愚公系列】2022年08月 Go教学课程 036-类型断言
pathman_config、pathman_config_params 删除后,如何重建?
How to delete statements audit log?
什么是三方支付?
What are port 80 and port 443?What's the difference?
DNS分离解析和智能解析
Element's BFC attribute
大马驮2石粮食,中马驮1石粮食,两头小马驮一石粮食,要用100匹马,驮100石粮食,如何分配?
VIT 源码详解
App Basic Framework Construction丨Log Management - KLog
Multi-serial port RS485 industrial gateway BL110
浅析一下期货程序化交易好还是手工单好?
Leetcode 669. 修剪二叉搜索树
Homework 8.10 TFTP protocol download function
Is Redis old?Performance comparison between Redis and Dragonfly
二叉树相关代码题【较全】C语言
Redis老了吗?Redis与Dragonfly性能比较
Description of ESB product development steps under cloud platform
The custom of the C language types -- -- -- -- -- - structure
The impact of programmatic trading and subjective trading on the profit curve!