转载

【浅度渣文】Jackson之jackson-annotations

  • @JsonProperty 可以指定字段的命名(还可以指定这个字段需要参与序列化和反序列化)。
    @JsonProperty.value
    @JsonProperty.index
    @JsonProperty.defaultValue
    

字段包含

  • @JsonAutoDetect :定义默认的字段包含规则
  • @JsonIgnore :忽略某个指定的字段:
    • 修饰字段,setter和getter中的任何一个,相当于所有都加了
      • 除非使用 @JsonProperty 修饰,可以实现只忽略序列化或者反序列化
  • @JsonIgnoreProperties :修饰类,指定忽略一个字段列表,或者忽略那些未知的字段
  • @JsonIgnoreType :修饰类,忽略指定的类型的字段
  • @JsonInclude :可以定义空值是否参与(反)序列化

字段文档,元数据

  • @JsonPropertyDescription :2.3支持,给字段配置人类阅读的解释
    • core和data-bind不会使用这个注解,主要是被 JSON Schema generator 这个模块使用

反序列化和序列化的细节

@JsonFormat
@JsonUnwrapped
@JsonView

@JsonUnwrapped(prefix = "pre") 简单解释:

public class MyValue {
    public String name;
    JsonUnwrapped(prefix = "pre_", suffix = "_suf")
    public MyValue myValue;
    public int age;
    public Date date;
}
复制代码

序列化结果:

{"name":"杨正","pre_name_suf":null,"pre_age_suf":0,"pre_date_suf":null,"age":24,"date":"2017-12-09"}
复制代码

@JsonView 简单解释:

public class JsonViewTest {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        String json = "{/"username/":/"dubby.cn/",/"password/":/"123456/"}";
        //反序列化,使用视图
        User user = objectMapper.readerWithView(User.UserWithoutPassword.class).forType(User.class).readValue(json);
        System.out.println(user);
        user.password = "xxxx";
        //序列化,使用视图
        String result1 = objectMapper.writerWithView(User.UserWithoutPassword.class).writeValueAsString(user);
        System.out.println(result1);
        String result2 = objectMapper.writerWithView(User.UserWithPassword.class).writeValueAsString(user);
        System.out.println(result2);
    }

}

class User {
    @JsonView({UserWithoutPassword.class})
    public String username;
    @JsonView({UserWithPassword.class})
    public String password;

    public interface UserWithPassword extends UserWithoutPassword {
    }

    public interface UserWithoutPassword {
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '/'' +
                ", password='" + password + '/'' +
                '}';
    }
}
复制代码

反序列化细节

  • @JacksonInject :指示某个字段的值是注入的,而不是从JSON中取出的
  • @JsonAnySetter :修饰一个2个参数的方法,任何JSON中有,而对象中没有的字段都会以(key,value)的形式传给这个方法
  • @JsonCreator :上篇文章自定义构造方法介绍过了
  • @JsonSetter :是 @JsonProperty 的替代注解
  • @JsonEnumDefaultValue :反序列化时,如果遇到未定义的枚举值时,赋值为默认枚举

@JsonAnySetter 简单解释:

public class JsonAnySetterTest {

    public static void main(String[] args) throws IOException {
        String json = "{/"username/":/"dubby.cn/",/"password/":/"123456/",/"x-key/":/"xxx-value/",/"y-key/":/"yyy-value/"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Data data = objectMapper.readValue(json, Data.class);
        System.out.println(data);
    }

}

class Data {

    public String username;

    public String password;

    public String other;

    @JsonAnySetter
    public void anySetter(String a, String b) {
        if (other == null) {
            other = "";
        }

        other += a;
        other += ",";
        other += b;
        other += ";";
    }

    @Override
    public String toString() {
        return "Data{" +
                "username='" + username + '/'' +
                ", password='" + password + '/'' +
                ", other='" + other + '/'' +
                '}';
    }
}
复制代码

输出:

Data{username='dubby.cn', password='123456', other='x-key,xxx-value;y-key,yyy-value;'}
复制代码

@JsonEnumDefaultValue 简单解释:

public class EnumTest {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true);

        String json = "{/"myEnum/":/"V4/"}";
        EnumData enumData = objectMapper.readValue(json, EnumData.class);
        System.out.println(enumData);
    }

}

class EnumData {
    public MyEnum myEnum;
    @Override
    public String toString() {
        return "EnumData{" +
                "myEnum=" + myEnum +
                '}';
    }
}

enum MyEnum {
    V1, V2, V3, @JsonEnumDefaultValue Default;
}
复制代码

输出:

EnumData{myEnum=Default}
复制代码

序列化细节

  • @JsonAnyGetter :修饰一个方法,返回 Map ,这个方法的返回值会被序列化成(key,value)形式
  • @JsonGetter : @JsonPropert 的替代注解
  • @JsonPropertyOrder :注定序列化的顺序
  • @JsonRawValue :被修饰的字段“准确”的显示出来,没有转义或装饰,双引号都不加
  • @JsonValue :指定序列化输出的值
  • @JsonRootName :使用这个指定的值作为JSON的根,前提是 SerializationFeature.WRAP_ROOT_VALUE 已经打开了

@JsonAnyGetter 简单解释:

public class JsonAnyGetterTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        AnyGetterData data = new AnyGetterData();
        data.data = "http://dubby.cn";
        System.out.println(objectMapper.writeValueAsString(data));
    }
}

class AnyGetterData {

    public String data;

    @JsonAnyGetter
    public Map other() {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        return map;
    }
}
复制代码

输出:

{"data":"http://dubby.cn","key1":"value1","key2":"value2","key3":"value3"}
复制代码

@JsonPropertyOrder 简单解释:

public class JsonPropertyOrderTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonPropertyOrderData data = new JsonPropertyOrderData();
        data.name1 = "value1";
        data.name2 = "value3";
        data.name3 = "value4";
        System.out.println(objectMapper.writeValueAsString(data));
    }
}

@JsonPropertyOrder(value = {"name2", "name3", "name1"})
class JsonPropertyOrderData {
    public String name1;
    public String name2;
    public String name3;
}
复制代码

输出:

{"name2":"value3","name3":"value4","name1":"value1"}
复制代码

@JsonValue 简单解释:

public class JsonValueTest {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json ="{/"name2/":/"value3/",/"name3/":/"value4/",/"name1/":/"value1/"}";
        JsonValueData data = objectMapper.readValue(json, JsonValueData.class);
        System.out.println(data.toString());
        System.out.println(objectMapper.writeValueAsString(data));
    }
}
class JsonValueData {
    public String name1;
    public String name2;
    public String name3;
    @JsonValue
    public String other() {
        return name1+name2+name3;
    }

    @Override
    public String toString() {
        return "JsonValueData{" +
                "name1='" + name1 + '/'' +
                ", name2='" + name2 + '/'' +
                ", name3='" + name3 + '/'' +
                '}';
    }
}
复制代码

输出:

JsonValueData{name1='value1', name2='value3', name3='value4'}
"value1value3value4"
复制代码

@JsonRootName 简单解释:

public class JsonRootNameTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
        RootData data = new RootData();
        data.name1 = "value1";
        data.name2 = "value2";
        data.name3 = "value3";
        System.out.println(objectMapper.writeValueAsString(data));
    }
}
@JsonRootName(value = "root")
class RootData {
    public String name1;
    public String name2;
    public String name3;
}
复制代码

输出:

{"root":{"name1":"value1","name2":"value2","name3":"value3"}}
复制代码
原文  https://juejin.im/post/5bc6d4905188255c4258590f
正文到此结束
Loading...