首页 > Java > java教程 > 正文

如何在Java中使用@JsonSerialize注解实现自定义序列化器?

WBOY
发布: 2023-09-11 18:17:06
转载
781 人浏览过

如何在Java中使用@JsonSerialize注解实现自定义序列化器?

@JsonSerialize 注解用于在字段序列化期间声明自定义序列化程序。我们可以通过扩展StdSeralizer类来实现自定义序列化器。并且需要重写StdSerializer类的serialize()方法。

语法

@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonSerialize
登录后复制

在下面的程序中,我们可以使用@JsonSerialize注解来实现自定义的序列化器

示例

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.ser.std.*;
public class JsonSerializeAnnotationTest {
   public static void main (String[] args) throws JsonProcessingException, IOException {
      Employee emp = new Employee(115, "Adithya", new String[] {"Java", "Python", "Scala"});
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// CustomSerializer class
class CustomSerializer extends StdSerializer {
   public CustomSerializer(Class t) {
      super(t);
   }
   public CustomSerializer() {
      this(Employee.class);
   }
   @Override
   public void serialize(Employee emp, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonGenerationException {
      StringBuilder sb = new StringBuilder();
      jgen.writeStartObject();
      jgen.writeNumberField("id", emp.getId());
      jgen.writeStringField("name", emp.getName());
      for(String s: emp.getLanguages()) {
         sb.append(s).append(";");
      }
      jgen.writeStringField("languages", sb.toString());
      jgen.writeEndObject();
   }
}
// Employee class
@JsonSerialize(using=CustomSerializer.class)<strong>
</strong>class Employee {
   private int id;
   private String name;
   private String[] languages;
   public Employee(int id, String name, String[] languages) {
      this.id = id;
      this.name = name;
      this.languages = languages;
   }
   public int getId() {
      return this.id;
   }
   public String getName() {
      return this.name;
   }
   public String[] getLanguages() {
      return this.languages;
   }
<strong>   </strong>@Override<strong>
 </strong>  public String toString() {
      StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name).append("\nLanguages:");
      for(String s: this.languages) {
         sb.append(" ").append(s);
      }
      return sb.toString();
   }
}
登录后复制

输出

{
   "id" : 115,
   "name" : "Adithya",
   "languages" : "Java;Python;Scala;"
}
登录后复制

以上是如何在Java中使用@JsonSerialize注解实现自定义序列化器?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板