Rename tag in xml using jakson

58 Views Asked by At

Please help, How can i rename tags in xml file usind jakson

My class:

public class Artist {
    private String name;
    private List<Album> albums = new ArrayList<>();
    public String getName() {
        return name;
    }
    public List<Album> getAlbums() {
        return albums;
    }
}
public class Album {
    private String name;
    private int year;
    public Album(String name, int year) {
        this.name = name;
        this.year = year;
    }
    @JacksonXmlProperty(isAttribute = true)
    public String getName() {
        return name;
    }    
    @JacksonXmlProperty(isAttribute = true)
    public int getYear() {
        return year;
    }
}

When i try to rename one tag <Albums> both are changed <Album>

i have:

    <Artist>
      <name>Some name</name>
      <albums>
        <albums name="Some name1" year="1985"/>
        <albums name="Some name2" year="1986"/>
      </albums>
    </Artist>

i want to see:

    <Artist>
      <name>Some name</name>
      <albums>
        <album name="Some name1" year="1985"/>
        <album name="Some name2" year="1986"/>
      </albums>
    </Artist>

do you have any idea?

1

There are 1 best solutions below

0
41 72 6c On

I think you can use the @JacksonXmlRootElement like this:

public class Album {
    private String name;
    private int year;
    
    @JacksonXmlRootElement(localName = "album")
    public Album(String name, int year) {
        this.name = name;
        this.year = year;
    }
    @JacksonXmlProperty(isAttribute = true)
    public String getName() {
        return name;
    }    
    @JacksonXmlProperty(isAttribute = true)
    public int getYear() {
        return year;
    }
}

This can be adapted with @JacksonXmlElementWrapper or @JacksonXmlProperty based on your structure.