Saturday, December 03, 2011

Using XStream to Map a Single Element

Let's say you have the following XML which has a single element containing an attribute and some text:
<error code="99">This is an error message</error>
and you would like to convert it, using XStream, into an Error object:
public class Error {
    String message;
    int code;

    public String getMessage() {
        return message;
    }

    public int getCode() {
        return code;
    }
}
It took me a while to figure this out. It was easy getting the code attribute set in the Error object, but it just wasn't picking up the message.

Eventually, I found the ToAttributedValueConverter class which "supports the definition of one field member that will be written as value and all other field members are written as attributes."

The following code shows how the ToAttributedValueConverter is used. You specify which instance variable maps to the value of the XML element (in this case message). All other instance variables automatically map to attributes, so you don't need to explicitly annotate them with XStreamAsAttribute.

@XStreamAlias("error")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"message"})
public class Error {

  String message;

  @XStreamAlias("code")
  int code;

  public String getMessage() {
      return message;
  }

  public int getCode() {
      return code;
  }

  public static void main(String[] args) {
      XStream xStream = new XStream();
      xStream.processAnnotations(Error.class);

      String xmlResponse="<error code=\"99\">This is an error message</error>";

      Error error = (Error)xStream.fromXML(xmlResponse);
      System.out.println(error.getCode());
      System.out.println(error.getMessage());
  }
}

2 comments:

  1. Thanks for the example.. I wish the XStream docs would provide an example when they add a feature.

    ReplyDelete
  2. Muchas Gracias, buena explicacion. Justo lo que necesitaba.

    ReplyDelete

Note: Only a member of this blog may post a comment.