Reputation: 7788
I'm trying to create a json object from my hibernate entity using jackson which can be posted to a remote url using jersey. I can't seem to figure out how to convert my hibernate entity to a json object. Using resteasy-jackson I was able to create my own web service accessible by localhost which outputted my json object correctly within my screen, but I was hoping to build the json object without having to use a webservice to my own app. Perhaps I'm going about this all the wrong way? I just don't want to manually have to add every property to a json object.
What I've tried thus far,
interface
@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);
}
class
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;
}
post service
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();
}
}
Company.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>
Upvotes: 0
Views: 7690
Reputation: 80633
If I understand what you are trying to do then you've written a lot of code that is not very useful for what you are trying to accomplish. For one, you're only supposed to define resource classes on the server side. And secondly, calling them directly is fraught with problems, they are server components that are supposed to be invoked by a container.
Good news is, the Jersey client is quite robust. It will automatically serialize your objects to an appropriate format, as long as its setup right. In your case, you want to make sure you are including the jersey-json JAR in your client. If you are, then you can have it automatically convert your object to JSON with the following code:
Company domainObject = companyDAO.findCompanyById(id);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
.entity(domainObject, MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
This code presumes that the server is responding with an instance of ClientResponse
. Also note that you need the jersey-json and Jackson JAR's in your client classpath in order for this to work. If using Maven its sufficient to include these dependencies:
<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>
Otherwise, you need to manually include all the right JAR's, minimum set:
Upvotes: 1
Reputation: 544
If I have understood you well you're looking for converting Java objects to their matching JSON representations. This is called JSON Serialization and you have some links here in "stackoverflow" itself talking about the matter
Upvotes: 0