2

SimpleXML library has issue. It ignores @Root name. Here is code with test:

Class:

@Root(name = "res", strict = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
class Response {

    @Attribute(name = "a")
    private Integer a;

    @Attribute(name = "i")
    private Integer i;

    @Attribute(name = "o", required = false)
    private Integer o;

}

Test:

    @Test
    public void detectXml() {

        Serializer serializer = new Persister();

        String xml = "<xxx a=\"1\" i=\"1\"/>";

        Response res = null;
        try {
            res = serializer.read(Response.class, xml);
        } catch (Exception e) {
            e.printStackTrace();
        }

        assertNotNull(res);

    }

Test passes no matter what is first tag in xml ie."<xxx" library ignores @Root name "res". Any suggestions beside to switch to another XML parser library? Can anyone suggest one with class annotations like SimpleXML?

Solata
  • 1,444
  • 3
  • 28
  • 42

1 Answers1

1
........
@Convert(Response.ResponseConverter.class)
class Response {

    ...........

    public static class ResponseConverter implements Converter<Response> {

        public ResponseTest read(InputNode node) throws Exception {
        String rootAnnotation = ResponseTest.class.getAnnotation(Root.class).name();
        if (!node.getName().equals(rootAnnotation) && node.isRoot()) {
            return null;
        }
        return new ResponseTest();
    }
        .................
    }
}



     @Test
public void detectXml() {

    Serializer serializer = new Persister();

    String xml = "<xxx a=\"1\" i=\"1\"/>";

    ResponseTest res = null;
    try {
        StringReader stringReader = new StringReader(xml);
        res = new Persister(new AnnotationStrategy()).read(ResponseTest.class, NodeBuilder.read(stringReader));
        if (res != null) {
            res = serializer.read(ResponseTest.class, xml);
        }
        System.out.println(res);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Assert.assertNotNull(res);
}

You can override the read method using @Converter annotation and validate the root name by fetching the Annotation value.

Colin Shah
  • 166
  • 3
  • 11
  • This works very well, but now in read() deserialization must be done manualy, even "required" annotation check for attribute "o" – Solata Apr 12 '21 at 12:36
  • Is possible to continue with automatic deserialization after @Root node compare in RestponseConverter.read() method? – Solata Apr 14 '21 at 11:26
  • There is some indirect way to do it, just check the edited answer. – Colin Shah Apr 15 '21 at 06:13