英文:
Remove and adding forward slash when serializing Path in Jackson
问题
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
英文:
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
答案1
得分: 1
尝试在你的POJO中添加用于序列化和反序列化的getter和setter。以下是一种方法。
@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());
}
英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论