Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

rest - A message body writer for Java class not found

I am new to using JAX-RS and wrote a sample application that outputs a json object. but I am getting an exception. Here is my code:

@Path("/hello")
public class HelloWorldService {

    @GET
    @Path("/query/{artist_id}")
    @Produces("application/json")
    public Data getMsg(@PathParam("artist_id") int artist_id,
                            @QueryParam("from") int from,
                            @QueryParam("to") int to) {
        Data d=new Data();
        d.setName("Mateen");
        d.setRoll(77);
        return d;

    }

}

My data is simply a POJO class:

@XmlRootElement
public class Data {
    private int roll;
    private String name;
    public int getRoll() {
        return roll;
    }
    public void setRoll(int roll) {
        this.roll = roll;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

I get an exception:

javax.ws.rs.WebApplicationException: 
    com.sun.jersey.api.MessageException: 
    A message body writer for Java class com.abc.data.Data, 
    and Java type class com.abc.data.Data, 
    and MIME media type application/json was not found

What am i doing wrong ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I finally found my answer. I added

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.8</version>
</dependency>

to my pom.xml file. Then I added

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

to my web.xml file, and everything works fine. No change was required to my code above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...