@JsonFormat 将 Collection、Number 序列化为 JSON 对象

@JsonFormat 还可以用于将 java.util.Collectionjava.lang.Number 的子类分别序列化为pojo而不是集合元素和数字标量值。只有在类级别使用 @JsonFormat#shape=JsonFormat.Shape.OBJECT 时才会起作用。可同时作用于序列化和反序列化。

Example

Java Objects

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class ArrayListEx<T> extends AbstractList<T> {
    private List<T> wrapperList = new ArrayList<>();
    ...
}    
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class BigIntegerEx extends BigInteger {
	...
}
public class Employee {
    private String name;
    private String dept;
    private ArrayListEx<String> phoneNumbers;
    private BigIntegerEx salary;
    ...
}    

Main class

public class ExampleMain {
    public static void main(String[] args) throws IOException {
        Employee employee = new Employee();
        employee.setName("Amy");
        employee.setDept("Admin");
        ArrayListEx<String> list = new ArrayListEx<>();
        list.add("111-111-111");
        list.add("222-222-222");
        employee.setPhoneNumbers(list);
        employee.setSalary(new BigIntegerEx("4000"));

        System.out.println("-- before serialization --");
        System.out.println(employee);

        System.out.println("-- after serialization --");
        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}
-- before serialization --
Employee{name='Amy', dept='Admin', phoneNumbers=[111-111-111, 222-222-222], salary=4000}
-- after serialization --
{"name":"Amy","dept":"Admin","phoneNumbers":{"wrapperList":["111-111-111","222-222-222"]},"salary":{"lowestSetBit":5}}

不使用 @JsonFormat

-- before serialization --
Employee{name='Amy', dept='Admin', phoneNumbers=[111-111-111, 222-222-222], salary=4000}
-- after serialization --
{"name":"Amy","dept":"Admin","phoneNumbers":["111-111-111","222-222-222"],"salary":4000}

原文链接

Jackson JSON - Using @JsonFormat to serialize Collection And Number As JSON Objects

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值