Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use java to generate json implementation to hide key attributes

Shulou Source: shulou.com Published: 2022-06-01 10:27:54 09月20日 Update

Editor to share with you how to use java to generate json implementation to hide the key attributes, I hope you will learn something after reading this article, let's discuss it together!

Java generates json to hide key attributes

Today, I encountered such a problem at work: when the backend returns data, some key or sensitive information does not want to be returned to the front end, but it is too lazy to define a dedicated DTO return (highly recommended, it is best to define a dedicated DTO return). For example, a user table has attributes such as user name, password, nickname, profile picture, gender and profile. Using @ ResponseBody to generate json direct username and password output to the foreground shows how the username and password attributes are hidden.

Spring Boot is used in our project, and Jackson is used as the serialization/deserialization of JSON by default.

So the solution is as follows

Annotations with @ JsonIgnore or @ JsonProperty will be fine

Private String password; @ JsonIgnorepublic String getPassword () {}

Or

@ JsonProperty (access = Access.WRITE_ONLY) private String password

In fact, there are many other methods, for example, you can write a filter to achieve, if you are using FastJson to Json string, you want to ignore the specified attribute can use the annotation @ JSONFie.

For example:

Public class FastJsonInputBean implements Serializable {private String contractTemplateId; private String contractId; @ JSONField (serialize = false) private String contractImage; private String contractVersion;} java entity to json ignore attribute import com.alibaba.fastjson.annotation.JSONField

Fastjson filter specified fields

@ JSONField (serialize=false) private String message

This field is not included when serialized.

In addition, you take only one field from a bean, there is no need to do so, you can define a new bean.

@ JsonIgnoreProperties (value= {"addressId"}) / / when parsing to json, the addressId field public class DicType {private String addressId;} @ JsonIgnoreprivate String img; of omitting sub-attributes has finished reading this article. I believe you have some understanding of "how to use java to generate json implementation to hide key properties". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

Tags: Attributes keys generation fields passwords users information comments user name article private necessary two personal profile front desk front end profile character string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MariaDB Xiaomi MySQL Shulou Tech Info