Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between the use of @ JSONField and @ JsonFormat

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the differences between @JSONField and @JsonFormat". In daily operation, I believe many people have doubts about the differences between @JSONField and @JsonFormat. I have consulted all kinds of materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "what are the differences between @JSONField and @JsonFormat"! Next, please follow the small series to learn together!

Difference between @JSONField and @JsonFormat

@JSONField is under fastjson under Alibaba,@JsonFormat is under jackson.

I. Common ways of @JSONField

1.1 Usage of name:

Entity class:

package com.xiaobu.entity; import com.alibaba.fastjson.annotation.JSONField;import lombok.Data; import javax.persistence.*; import java.io.Serializable; /** * @author xiaobu * @version JDK1.8.0_171 * @date on 2018/12/4 19:00 * @description V1.0 */@Datapublic class Roles implements Serializable { private static final long serialVersionUID = 5775171105018867238L; @JSONField(name = "role_id") @Column(name = "RoleId") private Integer RoleId; @JSONField(name = "role_desc") @Column(name = "RoleDesc") private String RoleDesc;}

Test Category:

/** * @author xiaobu * @date 2018/12/5 16:53 * @ desprition indicates that json is case-insensitive and can be converted * @version 1.0 * bean to JSON:{"role_desc":"admin","role_id":8} * json to be converted:{"ROLE_DESC":"ADMIN","ROLE_ID":8} * RoleDesc:ADMIN */ @Test public void testJSONField(){ Roles roles = new Roles(); roles.setRoleDesc("admin"); roles.setRoleId(8); String jsonStr=JSONObject.toJSONString(roles); System.out.println("bean to JSON:"+jsonStr); //change json key to upper case jsonStr = jsonStr.toUpperCase(); System.out.println("json:" + jsonStr); roles = JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), Roles.class); System.out.println("RoleDesc:"+roles.getRoleDesc()); }

1.2 Usage of format:

Entity class:

/** * task reception time */ @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") @JSONField(format = "yyyy-MM-dd") @Column(name="TaskAcceptTime") private Date TaskAcceptTime; /** :: Mission completion time */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") @JSONField(format = "yyyy-MM-dd") @Column(name="TaskCompleteTime") private Date TaskCompleteTime;

Test Category:

@Test public void findByExample() { Task task = new Task(); task.setTaskId("HYR08274-0804"); Example example = new Example(Task.class); Example.Criteria criteria = example.createCriteria(); if (StringUtils.isNotBlank(task.getTaskId())) { criteria.andLike("TaskId", "%" + task.getTaskId() + "%"); } //TaskAcceptTime=Mon Aug 04 00:00:00 CST 2008,TaskCompleteTime=Fri Nov 07 00:00:00 CST 2008 List tasks = taskMapper.selectByExample(example); System.out.println(tasks); //""taskAcceptTime":"2008-08-04","taskCompleteTime":"2008-11-07" String fastJsonStr = JSON.toJSONString(tasks); System.out.println("fastJsonStr = " + fastJsonStr); ObjectMapper MAPPER = new ObjectMapper(); try { //""TaskAcceptTime":"2008-08-04","TaskCompleteTime":"2008-11-07 00:00:00" String ujosn = MAPPER.writeValueAsString(tasks); System.out.println("ujosn = " + ujosn); } catch (JsonProcessingException e) { e.printStackTrace(); } }

@JsonFormat(pattern = "y-MM-dd",timezone = "GMT+8") must be added with time zone.

@JSONField(format = "yyyy-MM-dd")

Both are used to format dates and times. And it only works on dates and times.

Supplement: Front to background

@DateTimeFormat(pattern="y-MM-dd")@JsonFormat and @DateTimeFormat Usage and Notes @JsonFormat

@JsonFormat, jackson-related dependencies need to be added before using this annotation

Used to format Date type time when server passes data to front-end json

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

pattern indicates the format that needs to be changed, timezone indicates the time zone in which it is located (domestic is the East Eight Zone)

Because jackson is formatted according to GMT when serializing time, and CST time zone is used in domestic default time zone, the difference between the two is 8 hours

If the time is not formatted with @JsonFormat, a timestamp is returned to the front end. as shown in the figure.

When @JsonFormat is used, the time format is displayed correctly. as shown in the figure.

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

precautions

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

The case of the format defined in pattern should be paid attention to, do not write wrong...

@DateTimeFormat

@DateTimeFormat is an annotation of spring. There is no need to introduce additional dependencies under spring projects.

Since the time parameter passed by the client to the server is a string type, if you directly use Date under java.util.Date to accept it, an exception of 400 will be reported (400 exception means that the server will not process the request, most likely due to the passed parameter problem)

You can use @DateTimeFormat to convert the time parameter sent by the client to the desired type

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

pattern defines the format to be converted (same as before). Case needs to be strictly defined)

such

The server can receive correctly, and the printed time parameter is

Mon Apr 01 16:26:25 CST 2019

Note: @JsonFormat and @DateTimeFormat only define the format of the time parameter to be converted between the client and the server. Console, Debug display or java.util.Date type form. If you want to convert, you can use SimpleDateFormat yourself.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

some special cases

If the parameters of the above client are received using pattern = "y-MM-dd"

@DateTimeFormat(pattern = "yyyy-MM-dd")

This also receives correctly, but sets all hours, minutes and seconds to 00.

Mon Apr 01 00:00:00 CST 2019

If pattern = "y-MM-dd HH:mm:ss" is used to receive parameters without time, minutes and seconds from the client

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

400 abnormal!

At this point, the study of "what is the difference between @JSONField and @JsonFormat" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report