很少需要修复或添加的内容(不确定您的情况,因为缺少某些部分)
资源: 我自己进行了测试,因为您缺少一些项目
@Path("/")public class AccountResource { @GET @Path("/account") // route to a specific method.re @Produces(MediaType.APPLICATION_JSON) public Response saveDataIntoHash() { List<Account> accounts = new ArrayList<Account>(); accounts.add(new Account("Stack", "Savings")); accounts.add(new Account("Overflow", "Checkings")); GenericEntity generic = new GenericEntity<List<Account>>(accounts){}; return Response.status(201).entity(generic).build(); }}
假设您具有以下依赖性:
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>${jersey-version}</version></dependency>
测试用例: 注意客户端配置。这是必需的。
public void testMyResource() { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJaxbJsonProvider.class); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client c = Client.create(config); WebResource resource = c.resource(Main.base_URI); ClientResponse response = resource.path("account") .accept("application/json").get(ClientResponse.class); List<Account> accounts = response.getEntity(new GenericType<List<Account>>(){}); StringBuilder builder = new StringBuilder("=== Accounts ===n"); for (Account account: accounts) { builder.append("Name: ").append(account.getName()).append(", ") .append("Type: ").append(account.getType()).append("n"); } builder.append("=================="); System.out.println(builder.toString()); }
帐户(客户) 类缺少一个注释。在使用字段注释时,它是必需的。另一种选择是为
id
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) // <======= This Herepublic class Account { // added toString for testing @Override public String toString() { return "Account{" + "name=" + name + ", type=" + type + ", id=" + id + '}'; }}
*测试 *结果 :
=== Accounts ===Name: Stack, Type: SavingsName: Overflow, Type: Checkings==================
注意: 此测试基于服务器端没有错误的假设。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)