Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON XML - different names when serializing to XML

I'd like to have different name for my element when it's serialized to XML (for example "fooXml") and different for JSON (for example "fooJson"). Is it possible?

I'm using XML annotations like:

@XmlElements({
    @XmlElement(type = Foo.class, name = "fooXml"),
    })
    private SortedSet<Foo> fooSet;

I've tried already @JsonProperty, with without any luck.

I've also tried exporting it to getter method, like:

@XmlElement(type = Foo.class, name = "fooXml")
@JsonProperty(value = "fooJson")
public List<Foo> getFooList() {
    return new ArrayList<>(fooSet);
}

But it's always ignoring JSON annotations and serializing to XML form (fooXml name).

How shall I do it?

edit: I'm using Jersey-json.

like image 568
Greg Witczak Avatar asked Oct 15 '25 19:10

Greg Witczak


1 Answers

Alright, I had a need for this same functionality and found a solution that works for this:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

@JsonProperty("MyJsonName")
@JacksonXmlProperty(localName = "MyXmlName")
private MyProperty myProperty;

Works for me, and myProperty will be in the 'MyJsonName' field in Json and the 'MyXmlName' in XML.

like image 57
Bwvolleyball Avatar answered Oct 18 '25 08:10

Bwvolleyball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!