Home  >  Q&A  >  body text

Question: How to specify some attributes of the javaBean object and then convert it to a json string

There are many attributes in javabean, but in fact only some of the attributes need to be converted into json strings,

How can I control that only the specified attributes will be converted into json strings? ?

某草草某草草2645 days ago1109

reply all(4)I'll reply

  • 黄舟

    黄舟2017-06-28 09:26:15

    I don’t know where it is stored. If you need to serialize it, you can use the transient keyword.

    class User implements Serializable {
        private static final long serialVersionUID = 8294180014912103005L;  
        
        private String username;
        private transient String passwd;
        
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        public String getPasswd() {
            return passwd;
        }
        
        public void setPasswd(String passwd) {
            this.passwd = passwd;
        }
    
    }

    Among them, passwd is always null

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-28 09:26:15

    Try adding @JsonIgnore to the attribute to ignore it

    reply
    0
  • ringa_lee

    ringa_lee2017-06-28 09:26:15

    It depends on the framework you use to convert json. Different frameworks have different processing methods. It is recommended to read the documentation

    reply
    0
  • 欧阳克

    欧阳克2017-06-28 09:26:15

    1. Use the built-in methods of the JSON framework, such as the @JsonIgnore annotation provided by Jackson.

    2. Follow JsonIgnore and customize an annotation. During the conversion process, it is judged and processed through JAVA reflection and Annotated related classes. This method has strong customization ability. For example, all null values ​​​​can be not converted. Or convert the date attribute into different formats.

    3. Customize an intermediate class that only contains the attributes that need to be converted, then assign the data object to the intermediate class object, and finally convert the intermediate class object, so that the attributes that are not included will not appear.

    reply
    0
  • Cancelreply