我正在尝试使用 jackson 从我的 hibernate 实体创建一个 json 对象,可以使用 jersey 将其发布到远程 url。我似乎不知道如何将我的 hibernate 实体转换为 json 对象。使用resteasy-jackson,我能够创建自己的可通过localhost访问的Web服务,该服务在屏幕中正确输出我的json对象,但我希望构建json对象而不必在我自己的应用程序中使用Web服务。也许我的处理方式全错了?我只是不想手动将每个属性添加到 json 对象中。
到目前为止我已经尝试过,
界面
@Path("/company")
public interface CompanyResource {
@GET
@Produces("application/json")
public List<Company> getAllDomains();
@POST
@Produces("application/json")
public Response post(Company company);
@GET
@Path("{id}")
@Produces("application/json")
public Company getDomainObject(@PathParam("id") Integer id);
}
类
public List<Company> getAllDomains() {
return this.companyDAO.findAllCompanies();
}
public Response post(Company company) {
companyDAO.updateCompany(company);
return Response.ok().build();
}
public Company getDomainObject(@PathParam("id") Integer id) {
Company domainObject = this.companyDAO.findCompanyById(id);
if (domainObject == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return domainObject;
}
后期服务
public void setupRender() throws GeneralSecurityException, UnsupportedEncodingException {
try {
Client client = Client.create();
String url = kayakoWebService.generateURL();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
//Outputs object rather than json
System.out.println("test " + companyResource.getDomainObject(1));
} catch (Exception e) {
e.printStackTrace();
}
}
公司.class
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Company extends StatefulEntity {
@Validate("maxLength=50,required")
private String name;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date cancelDate;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date modifyDate;
@ManyToOne
@JoinColumn(name="parent_id")
private Company parent;
@Column(nullable = true, length = 5)
private Integer roomUnitCount;
@Column(nullable = false, length = 8)
private String accountNumber;
@JsonIgnore
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
//additional getters setters
}
cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.datasource">jdbc/domain</property>
<property name="hbm2ddl.auto">validate</property>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<property name="hibernate.generate_statistics">true</property>
</session-factory>
</hibernate-configuration>
最佳答案
如果我理解您想要做什么,那么您已经编写了很多代码,这些代码对于您想要完成的任务来说并不是很有用。其一,您只需要在服务器端定义资源类。其次,直接调用它们充满了问题,它们是应该由容器调用的服务器组件。
好消息是,Jersey 客户端非常强大。只要设置正确,它就会自动将您的对象序列化为适当的格式。就您而言,您需要确保在客户端中包含 jersey-json JAR。如果是,那么您可以使用以下代码让它自动将您的对象转换为 JSON:
Company domainObject = companyDAO.findCompanyById(id);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
.entity(domainObject, MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
此代码假定服务器正在使用 ClientResponse
实例进行响应。另请注意,您的客户端类路径中需要 jersey-json 和 Jackson JAR,才能使其正常工作。如果使用 Maven,则包含这些依赖项就足够了:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17</version>
</dependency>
否则,您需要手动包含所有正确的 JAR,最小集:
- jackson-core-asl-1.9.2.jar
- jackson-jaxrs-1.9.2.jar
- jackson-mapper-asl-1.9.2.jar
- jackson-xc-1.9.2.jar
- jersey-core-1.14.jar
- jersey-json-1.14.jar
- jersey-server-1.14.jar
关于java - Hibernate Entity 到 Json 对象,使用 jackson 到 http post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375328/