英文:
How to use Jackson @JsonFormat annotation to format a string on serialisation?
问题
我是Java的新手,正在使用Jackson将我的对象序列化为XML。我需要通过在HTML段落标签中包装字符串值来对其进行格式化。我尝试过使用@JsonFormat
注解,但没有成功。我的伪(代码)如下:
package mypackage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
public class MyClass {
// 我想找到一个模式,将文本序列化为<p>{text的字符串值}</p>
@JsonFormat(shape = Shape.STRING, pattern = "<p>{text}</p>") // 我可以像这样做些什么吗?
String text;
public MyClass(MyOtherClass otherClass) {
this.text = otherClass.text;
}
}
我无法找到任何关于如何使用pattern
来实现我想要的格式的文档。在这里使用@JsonFormat
是错误的方法吗?
英文:
I am a Java novice using Jackson to serialise my object into XML. I need to format my String values by wrapping them in HTML paragraph tags. I have tried using a @JsonFormat
annotation but without success. My pseudo(code) is below:
package mypackage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
public class MyClass {
// I want to find a pattern that will serialise text as <p>{string value of text}</p>
@JsonFormat(shape = Shape.STRING, pattern = "<p>{text}</p>") // can I do something like this?
String text;
public MyClass(MyOtherClass otherClass) {
this.text = otherClass.text;
}
}
I can't find any documentation on how to format pattern
to achieve what I want. Is using @JsonFormat
the wrong approach here?
答案1
得分: 1
你可以创建 JSON 的获取器(getter)和设置器(setter),然后使用自定义逻辑处理字段:
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@JsonGetter("text")
public String getJsonText() {
return text == null ? null : "<p>" + text + "</p>";
}
@JsonSetter("text")
public void setJsonText(String text) {
this.text = text == null ? null : StringUtils.substringBetween(text, "<p>", "</p>");
}
英文:
You can create json getter and setter and then process field with your custom logic:
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@JsonGetter("text")
public String getJsonText() {
return text == null ? null : "<p>" + text + "</p>";
}
@JsonSetter("text")
public void setJsonText(String text) {
this.text = text == null ? null : StringUtils.substringBetween(text, "<p>", "</p>");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论