Reputation: 85
What is the best way convert a JPA entity to JSON that does not include the related objects but the database columns.
Consider:
public class Question implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "question_title")
private String questionTitle;
@Size(max = 500)
@Column(name = "question_desc")
private String questionDesc;
@JoinColumn(name = "requires_question_id", referencedColumnName = "id")
@ManyToOne
private Question requiredQuestion;
...
}
Converting a Question directly to json may look like this:
{
"id": 1,
"questionTitle": "Q1",
"questionDesc": "A Question 123"
"requiredQuestion": {
"id": 2,
"questionTitle": "Q2",
"questionDesc": "A Question 456"
}
}
However a more desirable result may look like this:
{
"id": 1,
"question_title": "Q1",
"question_desc": "A Question 123"
"required_question_id": 2
}
What is the best way to obtain the desirable result?
Create a hashmap with String keys like "question_title", etc and manually assign the object properties, then convert the map to json?
Upvotes: 1
Views: 4865
Reputation: 87
In this type of application, you should not use the same object for comunicating with the client and for persisting data on your database. The reason is that is possible that your table estructure change for a requirement or for whatever and you have to change your JPA Entity. Also you have to change the client's code because the JPA Entity class change its structure.
You should create DTO, that is a simple POJO used for transfer information (serialization) to client and getting information from the client (deserializing). And use a library like Jackson or gson for transform Java object to Json format and the inverse.
Upvotes: 1
Reputation: 251
Assigning values manually to an object is not a good idea, because you can get your desirable result by projection in hibernate and then you can convert the map to json
return sessionFactory.getCurrentSession()
.createCriteria(Question.class)
.createAlias("requiredQuestion","requiredQuestion")
.setProjection(Projections.projectionList()
.add(Projections.property("id").as("id"))
.add(Projections.property("questionTitle").as("questionTitle"))
.add(Projections.property("questionDesc").as("questionDesc"))
.add(Projections.property("requiredQuestion.id").as("requiredQuestionid")))
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
.list();
This is the code to get the result what you are expecting and you can convert it to json.
Upvotes: 0
Reputation: 24423
You can use Jackson JSON Processor to serialize your entities to JSON just like any other POJO. To have full control on the output format, write a custom serializer for Question
class. It would look something like this
public class QuestionSerializer extends JsonSerializer<Question> {
@Override
public void serialize(Question value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.getId());
jgen.writeStringField("question_title", value.getQuestionTitle());
jgen.writeStringField("question_desc", value.getQuestionDesc());
jgen.writeNumberField("required_question_id", value.getRequiredQuestion().getId());
jgen.writeEndObject();
}
}
Upvotes: 2