我有一个简单的 hashmap 类,我想通过 Jersey 作为 JSON 发送。有没有人有一个关于如何执行这样一个操作的例子,我试过以下
package de.vogella.jersey.first;
import java.util.HashMap;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.view.Viewable;
// This method is called if XML is request
@GET
@Produces({ MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON })
public HashMap sayXMLHello() {
HashMap map = new HashMap();
map.put( new Integer( 2 ), "two" );
map.put( new Integer( 4 ), "four" );
return map;
}
// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
然后是客户端
package de.vogella.jersey.first;
import java.net.URI;
import java.util.HashMap;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Calls the HashMap function
System.out.println( service.path("rest")
.path("hello")
.accept(MediaType.APPLICATION_JSON)
.get(HashMap.class));
// The HTML
System.out.println(service.path("rest")
.path("hello")
.accept(MediaType.TEXT_HTML)
.get(String.class));
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.first").build();
}
}
一旦我部署并调用客户端类,我会收到以下错误:
Exception in thread "main" com.sun.jersey.api.client.UniformInterfaceException: GET http://localhost:8080/de.vogella.jersey.first/rest/hello
returned a response status of 500 Internal Server Error
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507)
at de.vogella.jersey.first.Test.main(Test.java:25)
那么关于如何使用 Jersey 将 HashMap 对象从服务器发送到客户端的任何想法?我也无法将 HashMap 对象映射到 POJO,因为没有统一的结构(一直在变化)
谢谢。