Reputation: 2332
We are creating a REST API for managing a resource. We are using Jersey
framework.
Following is the structure of the JSON
cable {
"id": 1,
"name": "Cable 1",
"description": "Test Cable",
"Site": 4
}
The JSON should map to the below class.
public class CableDTO {
private Long id;
private String name;
private String description;
//private SiteDTO site;
private Long siteID;
.
.
.
// Getters ans Setters
}
Site is actually a reference object. The input and output JSON, requires the CableDTO
to contain Site id instead of the entire Site
object. We have assemblers which convert the DTO's to Domain objects and vice-versa.
The sample assembler code is as below:
public class CableAssembler {
//some code
public void fillDomain(Cable cable, CableDto dto){
if(dto.getId() != null) cable.setID(dto.getId());
if(dto.getSiteID() != null) cable.setSiteId(dto.getSiteId())
//some more code below
}
}
This assembler works well when a brand new POST HTTP method is called. If the SiteID
is not set in the input json, the site is set to null and all is hunky dory. However, on a PUT HTTP call, if the SiteID
is not set, the existing SiteID
is over written to null
. This is because the same assembler is used in both PUT and POST call. The assembler checks if the siteID set in the DTO is null
. If it is null
, the existing siteID
is overwritten. The problem is, I am not able to distinguish between whether the null
value in the SiteID
is because the value was not sent or the SiteID
was indeed deliberately set to null
(which is possible {"siteID":null}
)
Any pointers on how to solve this?
We use Jackson
for serialization/de-serialization.
Upvotes: 0
Views: 126
Reputation: 2151
If I understood right your situation, my propositions are:
boolean
field to JSON and DTO telling if the siteID
was set and sent and check it in the assembler or other code;siteId
another default value, different from null
, like -1
or 0
, if it's possible.Upvotes: 1
Reputation: 2276
It seems that you use your PUT request like PATCH request. To use PUT request properly you should GET cable info, change some fields and PUT back. In this case your siteId field will remain unchanged.
Upvotes: 1