Skip to content

@JacksonXmlElementWrapper not respected when serializing Iterators / Iterables #148

@stanislawosinski

Description

@stanislawosinski

I'm using Jackson 2.5.2 to serialize objects both to JSON and XML. My use case involves serializing large dynamically generated collections, hence the need to expose an Iterator rather than a List for serialization.

Everything works perfectly with one snag: @JacksonXmlElementWrapper does not seem to be respected when serializing Iterator / Iterable. I'd expect the following code:

public class WrapperTest {
  public static void main(String[] args) throws IOException {
    new XmlMapper().writeValue(System.out, new ToSerialize());
  }

  private static class ToSerialize {
    @JsonProperty("item")
    @JacksonXmlElementWrapper(localName = "list")
    public Iterator<String> items() {
      return new Iterator<String>() {
        int item = 4;

        @Override
        public boolean hasNext() {
          return item > 0;
        }

        @Override
        public String next() {
          item--;
          return Integer.toString(item);
        }
      };
    }
  }
}

to produce:

<ToSerialize><list><item>3</item><item>2</item><item>1</item><item>0</item></list></ToSerialize>

but instead I'm getting:

<ToSerialize><item>3</item><item>2</item><item>1</item><item>0</item></ToSerialize>

Am I doing anything wrong here?

If I replace the Iterator with a List, the wrapping element gets correctly added, but switching to in-memory lists is not practical in our use case. I could instead return a dummy list that returns my original iterator in the iterator() method (and throws UnsupportedOperationException in all other methods), but this seems a rather ugly hack.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions