我正在尝试使用Jackson的@JsonDeserialize(builder = class)
注释示例来允许构建器模式。我试图使用我的对象,但一直遇到错误。然后我从杰克逊网页上复制了这个例子,但它仍然没有用。
这是我的示例文件:
数据项
package org.cpicard.finance;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(builder=ExampleBuilder.class)
public class Example {
private final int x, y;
protected Example(int x, int y) {
this.x = x;
this.y = y;
}
}
生成器
package org.cpicard.finance;
public class ExampleBuilder {
private int x, y;
public ExampleBuilder () { }
public ExampleBuilder withX(int x) {
this.x = x;
return this;
}
public ExampleBuilder withY(int y) {
this.y = y;
return this;
}
public Example build() {
return new Example(x, y);
}
}
休息服务
package org.cpicard.finance;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cpicard.model.finance.Example;
@Path("/account")
public class AccountService {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("test1")
public Response createAccount1(final Example account) {
System.out.println(account.toString());
return Response.ok().build();
}
}
应用程序配置
package org.cpicard.finance;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rs")
public class ApplicationConfig extends Application {
private final Set<Class<?>> classes;
public ApplicationConfig() {
final HashSet<Class<?>> c = new HashSet<>();
c.add(AccountService.class);
classes = Collections.unmodifiableSet(c);
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}
Web xml代码段
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>org.cpicard.finance.ApplicationConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rs/*</url-pattern>
</servlet-mapping>
这会导致以下错误:
[2015-03-01T10:30:19.576-0700] [glassfish 4.1] [SEVERE] [] [org.glassfish.jersey.message.internal.ReaderInterceptorExecutor] [tid:_ThreadID = 31 _ThreadName = http-listener-1(4)] [timeMillis: 1425231019576] [levelValue:1000] [[未找到MessageBodyReader media type = application / json,type = class org.cpicard.model.finance.Example,genericType = class org.cpicard.model.finance.Example。]]
当我将数据项切换到具有常规getter和setter的标准对象时,它可以正常工作。我认为我的配置有些不正确,但不确定它可能是什么。
使用Glassfish 4.1