我正在学习使用REST的Java 8,从我的微服务中我调用了一个REST服务,并收到了一个JSON对象。之后,我需要删除开头和结尾的空格,然后将其发送到前端。
例如,我有一个模型对象:
public class User {
@JsonProperty("name")
private String name = null;
@JsonProperty("education")
private String education = null;
@JsonProperty("phone")
private String phone = null;
@JsonProperty("age")
private String age = null;
public User() {
}
........
}
所以我打电话给这个外部服务,我收到了这样的回复:
{
"name": " John Book",
"education": " Faculty of Computers ",
"phone": "00448576948375 ",
"age": " 20 "
}
现在,我需要为每个字段从开始到结束清理所有空间,并将其转换为
{
"name": "John Book",
"education": "Faculty of Computers",
"phone": "00448576948375",
"age": "20"
}
我该如何实现这种功能?非常感谢。
只需在每个字段上使用String#trim()
就可以了。但是,我建议在您第一次从前端接收JSON时,甚至在后端持久化之前删除空白。将传入的JSON整理到Java POJO:时插入以下行
User user = ... // marshall from JSON
user.setName(user.getName().trim());
user.setEducation(user.getEducation().trim());
user.setPhone(user.getPhone().trim());
user.setAge(user.getAge().trim());
UI不希望看到这个空白,这意味着将它存储在后端可能没有意义。