java序列化类添加字段,Java如何在序列化期间使用Jackson ObjectMapper连接Item类中的两个字段?...

I have a class:

public class Item {

private String firstName;

private String lastName;

private int age;

}

When I convert it to JSON, I would like to combine the firstName and lastName fields. So something like:

ObjectMapper objMapper = createMapper();

Item item = new Item("Bob", "Smith", 190);

String json = objMapper.writeValueAsString(item);

But I would like the json to look as follows:

{

"Name": "Bob Smith",

"age" : "190"

}

instead of:

{

"firstName": "Bob",

"lastName" : "Smith",

"age" : "190"

}

Like wise, I would like to go the other way around. So if String anotherString is,

{

"Name": "Jon Guy",

"age" : "20"

}

objMapper.readValue(anotherString, Item);

should produce an Item with firstname = Jon, lastName = Guy, age = 20

解决方案

As a general heads up, https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations are going to tell you what annotations will help you with jackson stuff.

Anyway, two things are happening here:

You want to serialize an additional field

You want to parse that additional field out from your object (I'll actually caution against this below)

I'm assuming you want to store the name field together, possibly for display purposes.

Given my experience I'm going to caution you against actually parsing the fullName property out of any incoming JSON, because it's actually non trivial (for example, imagine a person named Lauren de Silva).

The solution I'm going to present is going to serialize the object with a name property, but will ignore that property when the object is read back in.

What we're going to do is customize your POJO, rather than doing any special serialization code:

public class Item {

private String firstName;

private String lastName;

private int age;

@JsonProperty("Name",access=Access.READ_ONLY)

public String getName() {

return(firstName + " " + lastName);

}

}

I would of course recommend adding null checking to the various methods if your firstName or lastName could be blank or null.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值