java - Grizzly 在 MediaType.Application_JSON 上失败

标签 java rest maven jersey-2.0 grizzly

我正在关注pluralsight.com 上关于如何设置grizzly 服务器和创建rest api 的教程。 如果我的方法@产生平面文本=那么一切正常,但如果我有api方法返回我一个json文件,而不是我得到

  Pom.file >>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.plurasight</groupId>
    <artifactId>async-rest</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>async-rest</name>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
        </dependency>
        <!-- uncomment this to get JSON support:
         <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.plurasight.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jersey.version>2.7</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Java 类文件:

 BookDao



public class BookDao {
    private HashMap<String, Book> books;

    BookDao() {
        books = new HashMap<String, Book>();

        Book book1 = new Book();
        book1.setId("1");
        book1.setAuthor("Gino");
        book1.setTitle("Gino's book1");
        book1.setAspn("1234");
        book1.setPublishedDate(new Date());


        Book book2 = new Book();
        book1.setId("2");
        book1.setAuthor("Gino2");
        book1.setTitle("Gino's book2");
        book1.setAspn("2234");
        book1.setPublishedDate(new Date());


        Book book3 = new Book();
        book1.setId("3");
        book1.setAuthor("Gino");
        book1.setTitle("Gino's book1");
        book1.setAspn("3234");
        book1.setPublishedDate(new Date());

        books.put(book1.getId(), book1);
        books.put(book2.getId(), book2);
        books.put(book3.getId(), book3);

    }

    List<Book> getBooks() {
        List<Book> list = new ArrayList<Book>(books.values());

        return list;
    }

}

图书资源:

@Path("/books")
public class BookResource {

    BookDao dao = new BookDao();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBooks() {
        System.out.println("PRINTLINE FROM BOOKS API");
//        GenericEntity<List<Book>> entity = new GenericEntity<List<Book>>( dao.getBooks() ){};
        GenericEntity<List<Book>> entity = new GenericEntity<List<Book>>(dao.getBooks()) {
        };

        return Response.ok(entity).build();
    }

}

主类:

public class Main {
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    public static HttpServer startServer() {
        final ResourceConfig rc = new ResourceConfig().packages("com.plurasight");
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        System.in.read();
        server.stop();
    }
}

wadl 的回复

<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.7 2014-03-12 18:11:31"/>
<doc xmlns:jersey="http://jersey.java.net/" jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8080/myapp/application.wadl?detail=true"/>
<grammars/>
<resources base="http://localhost:8080/myapp/">
<resource path="/books">
<method id="getBooks" name="GET">
<response>
<representation mediaType="application/json"/>
</response>
</method>
</resource>
<resource path="myresource">
<method id="getIt" name="GET">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
</resources>
</application>

对/getBooks api 的响应

PRINTLINE FROM BOOKS API
Oct 31, 2014 11:11:58 AM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<com.plurasight.Book>.

最佳答案

Cássio Mazzochi Molin评论是正确的!

您需要使用GenericEntity :

Represents a response entity of a generic type T.
Normally type erasure removes generic type information such that a Response instance that contains, e.g., an entity of type List<String> appears to contain a raw List<?> at runtime.

因此你需要实现类似的东西:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getDrivers() {
    System.out.println("printline from drivers api");
    GenericEntity<List<Driver>> entity = new GenericEntity<List<Driver>>( dao.getDrivers() ){};
    return Response.ok(entity).build();
}

编辑(更新的问题)

除了您的依赖项之外,我没有看到任何问题。请添加MessageBodyWriter/-Reader通过添加正确的依赖项来支持。

我在构建中使用的资源(Tomcat 7)是:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.bundles</groupId>
        <artifactId>jaxrs-ri</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-processing</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
    </dependency>

祝你有美好的一天...

关于java - Grizzly 在 MediaType.Application_JSON 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667375/

相关文章:

rest - 在使用HATEOAS时找到 Restful 资源?

web-services - Grails Rest简单计算器示例

java - Maven Surefire 插件未进行测试

java - JPA 获取连接实体返回递归获取循环

java - Android 通知监听器服务自行启动

django - 使用 REST 框架查询 URL 中的参数

spring - 尝试将 JPA 与 Kotlin 和 Spring boot 结合使用时出现 BeanDefinitionParsingException

Java JDBC MySQL 查询失败

java - Java中getAbsolutePath的打印

java - 尝试使用另一个类中的方法时,线程 "main"java.lang.NullPointerException 中出现异常?