如何使用Jackson的@JsonFormat注解在序列化时格式化字符串?

huangapple go评论65阅读模式
英文:

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(&quot;text&quot;)
    public String getJsonText() {
        return text == null ? null : &quot;&lt;p&gt;&quot; + text + &quot;&lt;/p&gt;&quot;;
    }

    @JsonSetter(&quot;text&quot;)
    public void setJsonText(String text) {
        this.text = text == null ? null : StringUtils.substringBetween(text, &quot;&lt;p&gt;&quot;, &quot;&lt;/p&gt;&quot;);
    }

huangapple
  • 本文由 发表于 2020年9月28日 20:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64101956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定