Getting error A message body writer for Java class

2019-01-15 23:42发布

问题:

well this has been posted a lot of time here but no solution worked for me...
i can avoid this error by making a wrapper class but it only returned

</stringWrapper>

what am i doing wrong ?

StringWrapper class:

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class StringWrapper {
    public StringWrapper (){}

    List<String> list=new ArrayList<String>();

    public void add(String s){ 
        list.add(s);
    }
}

code :

     @Path("/xml")
     @GET
     @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
     public StringWrapper mystring(){
        StringWrapper thestring=new StringWrapper();
        thestring.add("a");
        thestring.add("a");
        return thestring;
     }

Java Rest webservice using Jersey.

回答1:

You should add at least a getter in your StringWrapper. Without public attributes, there is nothing to serialize. So the output is correct. If you do not want a tag around the list of your strings, you can mark a single getter with @XmlValue.

@XmlRootElement
public class StringWrapper {
    public StringWrapper (){}

    List<String> list=new ArrayList<String>();

    public void add(String s) { list.add(s); }

    @XmlValue    
    public List<String> getData() { return list; }

}