Reputation: 1804
I am working with two APIs. One has all its paths with leading forward slashes, and the other does not. I have decided to normalize my application and use a leading forward slash for all paths (since none of the paths are relative).
If I submit JSON to API with non leading slash, with a value used for a path that has leading slash on the path, it will produce an error.
Is there any way to modify the following class so that, when it is deserialized, the Path has a leading slash, and when serialized it has no leading slash, just for this specific POJO?
public class FilePOJO {
@JsonProperty("path")
public Path path;
}
e.g.
FilePOJO fp = new FilePOJO();
fp.path = Paths.get("/some/path/file.txt");
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(fp));
// {"path": "some/path/file.txt"}
final FilePOJO filePOJO = om.readValue("{\"path\": \"some/path/file.txt\"}", FilePOJO.class);
System.out.println(filePOJO.path.toString());
// /some/path/file.txt
Upvotes: 0
Views: 481
Reputation: 183
Try adding getters and setters to your POJO which are used while serialization and deserialization. Below is one way of doing it.
@JsonProperty("path")
public Path getPath() {
return Paths.get(path.toString().substring(1));
}
@JsonProperty("path")
public void setPath(Path path) {
this.path = Paths.get("/", path.toString());
}
Upvotes: 1