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

How to configure jackson in springboot

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

Share

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

This article mainly introduces how to configure jackson in springboot. The article is very detailed and has certain reference value. Interested friends must read it!

springboot jackson configuration

The json used in the project is jackson. This is what Spring Boot comes with. At first, it was fastjson by Ali. But there are always loopholes. Jackson, google's gson also feels great.

demand

Use @RestController in controller to return json. It was Jackson. When dealing with BigDecimal, you want to remove 00 after the decimal point, such as 280.00.

global configuration

This requirement must be configured globally. Read the document, configure it, feel it can also write it.

import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.json.JsonReadFeature;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.json.JsonMapper;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import java.io.IOException;import java.math.BigDecimal;import java.text.DecimalFormat;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;/** * @Author: plani * Created: 2020/9/22 9:41 */@Configurationpublic class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper() { JsonMapper.Builder builder = JsonMapper.builder(); //Set the mapper object with this method, and all serialized objects will be serialized according to the change rules // Include.Include.ALWAYS Default // Include.NON_DEFAULT attribute is default value not serialized // Include.NON_EMPTY attribute is empty ("") or NULL is not serialized, then the returned json is without this field. This will save more traffic on the mobile side // Include.NON_NULL property is NULL not serialized builder.serializationInclusion(JsonInclude.Include.NON_EMPTY); //Do you want to throw an exception if there are unknown attributes builder.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //Whether to allow JSON strings to contain the property of unescaped control characters (ASCII characters with values less than 32, including tabs and newlines). If feature is set to false, an exception is thrown when such a character is encountered. builder.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS, true); //Determines whether the parser allows attributes of strings (names and string values) to be referenced using single quotes (apostrophe, character '\ "). If yes, this is in addition to other acceptable markers. But not the JSON specification). builder.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); JsonMapper jsonMapper = builder.build(); JavaTimeModule javaTimeModule = new JavaTimeModule(); //Add sequencer Here is BigDecimal type processing, this is the key code javaTimeModule.addSerializer(BigDecimal.class, new JsonSerializer() { @Override public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException { DecimalFormat fnum = new DecimalFormat("#.## "); //Write the value corresponding to this BigDecimal attribute as String type gen.writeString(fnum.format(value)); } }); //processing time format javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); //Register jsonMapper.registerModule(javaTimeModule); return jsonMapper; }}

The most important one above is the addSerializer method, which handles the conversion of the corresponding type. Comments are very clear, do not understand the message can ask me.

additional

There are a lot of ObjectMapper settings on the Internet, and many of them are marked obsolete. So I used JsonMapper.

test

Write a controller method that returns a class containing BigDecimal to test it.

@PostMapping("test") public Map test() { Map map = new HashMap(); BigDecimal bigDecimal = new BigDecimal("280.00"); map.put("one", bigDecimal); return map; }

Test with postman.

You can see that 280.00 has been converted to 280. All right, I'm off to deep learning.

springboot configure jackSon processing field

Common frameworks: ali, fastjson, google, gson, etc.

javaBean serializes to json

Performance: Jackson > Fastjson > Gson > Json-lib Same Structure

Jackson, Fastjson, Gson class libraries have their own characteristics, each has its own expertise

③ Space for time, time for space

Jackson processes correlation automatically

① Specify the field does not return: @jsonIgnore (mainly used for passwords, so that passwords are not displayed, added to the field above)

② Specify date format: @JsonFormat(pattern = "y-MM-dd hh:mm:ss",locale = "zh",timezone = "GMT+8")

③ Empty field does not return: @JsonInclude(JsonInclude.Include.NON_NULL)

③ Specify alias: @JsonProperty("create_time")

Development function: return custom format when video is created, filter user sensitive information.

private int price; @JsonProperty("cover_img") private String coverImg; @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "zh",timezone = "GMT+8") @JsonProperty("create_time") private Date createTime; @JsonInclude(JsonInclude.Include.NON_NULL) private List chapterList; The above is all the content of this article "How to configure jackson in springboot", thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

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