Henk
Henk

Reputation: 29

Weird response JAX-RS when producing XML

I've currently having some problems unmarshalling XML that I marshalled myself. It took me some time to figure it out, because I thought the marshalling went nicely (no exceptions etc.). The method that produces my XML returns:

<?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8" standalone="yes" 
    <TestClass> 
        <testValue>banaan</testValue> 
    </TestClass>

But suddenly I had the very obvious realization (much too late), that the XML produced isn't correct at all. It should obviously be:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
    <TestClass> 
        <testValue>banaan</testValue> 
    </TestClass>

How is it possible that this very simple code:

@Path("test")
@GET
@Produces(MediaType.APPLICATION_XML)
public TestClass getTestClass() {
    TestClass test = new TestClass();
    test.setTestValue("banaan");
    return test;
}

And the TestClass:

@XmlRootElement(name = "TestClass")
public class TestClass {

private String testValue;   

@XmlElement(name = "testValue")
public String getTestValue() {
    return testValue;
}

public void setTestValue(String testValue) {
    this.testValue = testValue;
}

public TestClass() {

}

}

produces invalid XML? And more importantly, how can I fix it?

Upvotes: 1

Views: 118

Answers (2)

LINEMAN78
LINEMAN78

Reputation: 2562

You are using the default attempt to create a JAXBContext which should function correctly, however it seems to be messing up somehow. Try adding a custom context resolver to your application.

@Provider
public class XmlContextProvider implements ContextResolver<JAXBContext> {
    private JAXBContext context = null;

    public JAXBContext getContext(Class<?> type) {
        if (type != TestClass.class) {
            return null; // we don't support nothing else than TestClass
        }

        if (context == null) {
            try {
                context = JAXBContext.newInstance(TestClass.class);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
        }
        return context;
    }
}

You will also have to add XmlContextProvider to your Application class.

Upvotes: 1

jake delhome
jake delhome

Reputation: 1

How are you marshalling the code? It seems like you are setting the class and its values properly, but it may be an issue with how you are creating the marshall object and the context/formatted output you are using

Here is an example JAXBContext context = JAXBContext.newInstance(TestClass.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter stringWriter = new StringWriter(); m.marshal(test, stringWriter); return stringWriter.toString();

Did you do something along these lines?

Upvotes: 0

Related Questions