如何清除Java中首尾的空格?

How to clean the spaces from the beginning and the end in Java?

我正在使用 REST 学习 Java 8,我正在从我的微服务中调用 REST 服务并收到一个 JSON 对象。之后,我需要从头到尾删除 space,然后将其发送到前端。

例如我有这个模型对象:

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 "
}

现在我需要清除每个字段开头和结尾的所有 space,并将其转换为:

{
    "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 不想看到这个空白意味着首先将它存储在后端可能没有意义。