2012-02-28 26 views
6

繼說明here我有這樣的代碼:如何在澤西使用Grizzly2以編程方式啓用POJO映射?

private static URI getBaseURI() { 
    return UriBuilder.fromUri("http://localhost/").port(9998).build(); 
} 

public static final URI BASE_URI = getBaseURI(); 

protected static HttpServer startServer() throws IOException { 
    System.out.println("Starting grizzly..."); 
    final ResourceConfig rc = new PackagesResourceConfig("amplify.api.resources"); 
    return GrizzlyServerFactory.createHttpServer(BASE_URI, rc); 
} 

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

接下來我想啓用JSON支持POJO描述here,但問題是,我想這樣做編程方式,而不是通過web.xml文件(我沒有web.xml文件!)。

如何修改上面的代碼來啓用JSON POJO映射功能?

回答

10
protected static HttpServer startServer() throws IOException { 
    System.out.println("Starting grizzly..."); 
    final ResourceConfig rc = new PackagesResourceConfig("amplify.api.resources"); 
    rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); 
    return GrizzlyServerFactory.createHttpServer(BASE_URI, rc); 
} 
2

您只需要將jersey-json庫添加到您的項目。

如果您正在使用Maven,只需添加這種依賴性:

<dependency> 
    <groupId>com.sun.jersey</groupId> 
    <artifactId>jersey-json</artifactId> 
    <version>${jersey.version}</version> 
</dependency> 

這對我的作品即便是不添加JSONConfiguration.FEATURE_POJO_MAPPING到ResourceConfig的的feautres。

相關問題