0

I'm learning Java 8 with REST and from my microservice I'm calling a REST service and I receive a JSON object. After that I need to delete the space from beginning and the end and after that to send it to frontend.

For example I have this model object:

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() {
    }

    ........
}

So I'm calling this external service and I receive this kind of response:

{
    "name": "  John Book",
    "education": "   Faculty of Computers            ",
    "phone": "00448576948375           ",
    "age": "   20 "
}

Now I need to clean all the spaces from the begining and the end for every field and to transform it in this:

{
    "name": "John Book",
    "education": "Faculty of Computers",
    "phone": "00448576948375",
    "age": "20"
}

How can I do this kind of implementation? Thank you!

vahdet
  • 6,357
  • 9
  • 51
  • 106
elvis
  • 956
  • 9
  • 33
  • 56

1 Answers1

3

Simply using String#trim() on each of the fields might work here. But I suggest removing the whitespace before you even persist on your backend, at the time when you first receive the JSON from the front end. Insert the following lines when you marshall the incoming JSON to the 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());

That the UI doesn't want to see this whitespace implies that there might not be a point in storing it on the backend in the first place.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360