java 自定义注解 生成json_Java使用@JsonDeserialize注解实现自定义反序列化器

@JsonDeserialize注解用于在将JSON反序列化为Java对象时声明自定义反序列化器。我们可以通过使用泛型类型Employee继承 StdDeserializer类来实现自定义反序列化器,并且需要重写StdDeserializer类的deserialize()方法。

语法@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})

@Retention(value=RUNTIME)

public @interface JsonDeserialize

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

示例import java.io.*;

import com.fasterxml.jackson.core.*;

import com.fasterxml.jackson.databind.*;

import com.fasterxml.jackson.databind.annotation.*;

import com.fasterxml.jackson.databind.deser.std.*;

public class JsonDeSerializeAnnotationTest {

public static void main (String[] args) throws JsonProcessingException, IOException {

Employee emp = new Employee(115, "Adithya");

ObjectMapper mapper = new ObjectMapper();

String jsonString = mapper.writeValueAsString(emp);

emp = mapper.readValue(jsonString, Employee.class);

System.out.println(emp);

}

}

// CustomDeserializer 类

class CustomDeserializer extends StdDeserializer {

public CustomDeserializer(Class t) {

super(t);

}

public CustomDeserializer() {

this(Employee.class);

}

@Override

public Employee deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException

{

int id = 0;

String name = null;

JsonToken currentToken = null;

while((currentToken = jp.nextValue()) != null) {

switch(currentToken) {

case VALUE_NUMBER_INT:

if(jp.getCurrentName().equals("id")) {

id = jp.getIntValue();

}

break;

case VALUE_STRING:

switch(jp.getCurrentName()) {

case "name":

name = jp.getText();

break;

default:

break;

}

break;

default:

break;

}

}

return new Employee(id, name);

}

}

// Employee 类

@JsonDeserialize(using=CustomDeserializer.class)

class Employee {

private int id;

private String name;

public Employee(int id, String name) {

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public String getName() {

return name;

}

@Override

public String toString() {

StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name);

return sb.toString();

}

}

输出结果ID: 115

Name: Adithya


版权声明:本文为weixin_29643235原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。