Java how to use Jackson ObjectMapper to concatenate two fields in Item class during serialization?

∥☆過路亽.° 提交于 2019-12-24 17:00:01

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/38084705/java-how-to-use-jackson-objectmapper-to-concatenate-two-fields-in-item-class-dur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!