Ed Graham
Ed Graham

Reputation: 4705

How to use Jackson @JsonFormat annotation to format a string on serialisation?

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?

Upvotes: 1

Views: 2018

Answers (1)

Egor
Egor

Reputation: 1409

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>");
    }

Upvotes: 1

Related Questions