Reputation: 626
The needed Class for solving the problem of passing 2 objects in method.I will appreciate if anybody will give better solution for this.
public TransferObject {
public long tid;
public String tname;
public String tlastname;
public String tmessage;
Message mess = new Message(tmessage);
Person pers = new Person(tid,tname,tlastname);
public Person getPerson() {
return pers;
}
public Message getMessage() {
return mess;
}
}
Mine post method: Here I solved the solution of passing 2 objects as one:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Comment addComment(TransferObject transfer){
Person p = transfer.getPerson();
Message m = transfer.getMessage();
Person pers = new Person(p.getId(),p.getName(),p.getLastName());
Message mess = new Message(m.getMessage());
Comment comment = new Comment(mess);
comment = new CommentService().addComment(comment, pers);
return comment;
}
Mine JSON input:
{
"tid":"320598",
"tname":"Maks",
"tlastname":"Burkov",
"tmessage":"I Love Runing"
}
JSON Output:
Map <Long,Comment> comments = new HashMap();
{
"message": {
"created": "2016-04-30 18:25 PM GMT",
"message": null,
"messageID": 1
},
"id": 1,
"date": "2016-04-30 18:25 PM GMT"
}
All information is passing as I see.. But the message is not. Here I got message null. If anybody can help me will be great..
Upvotes: 0
Views: 139
Reputation: 692231
Well, look at your class:
public class TransferObject {
public long tid;
public String tname;
public String tlastname;
public String tmessage;
Message mess = new Message(tmessage);
Person pers = new Person(tid,tname,tlastname);
public Person getPerson() {
return pers;
}
public Message getMessage() {
return mess;
}
}
The mess
and pers
fields are initialized when the constructor is called. At that time, all the other fields have their default, null value. It's only after the object is conctructed that the fields are initialized from their JSON value.
For the code to work, it would have to look like
public Person getPerson() {
return new Person(tid, tname, tlastname);
}
public Message getMessage() {
return new Message(tmessage);
}
But why don't you simply design your JSON with the right structure from the start:
class TransferObject {
private Message message;
private Person person;
}
and the JSON would have the sme structure:
{
"person": {
"tid":"320598",
"tname":"Maks",
"tlastname":"Burkov"
},
"message": {
"tmessage":"I Love Runing"
}
}
BTW, why this t
prefix. Why not just call the fields "id", "name", "lastName"? Isn't that much more readable?
Upvotes: 1