Convert JSON to Object with JAXB only if all fields are filled
I am creating a RESTful web service from Jersey. I am using JAXB to convert incoming JSON objects to Java objects. Unfortunately, this approach allows you to create Java objects that don't have all of the required fields. If I have 3 required fields, but the JSON only contains 1 field, I would like an exception to be thrown.
Resource class:@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Resource {
private int field1;
private String field2;
private String field3;
public Resource() {
}
...
}
REST class:
@Path("resource")
public class ResourceREST {
...
@POST
@Consumes(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
public String createResource(Resource resource) {
...
}
...
}
Is there a way to do this with JAXB? If not, how can I implement this input validation?
Thanks in advance!
I went through the same scenario and applied some logic to fix this after creation JSON
.
In the list, add those Field Names
that you think are required.
public static final List<String> REQUIRED_FIELDS = new ArrayList<String>();
static {
REQUIRED_FIELDS.add("Field1");
REQUIRED_FIELDS.add("Field2");
};
Submit the ones JSON
you created for the validation method.
Your verification method should be like this.
public void validateRequiredFields(JSONObject jsonObject, List<String> requiredFields) throws ParserException, Exception {
if (log.isDebugEnabled()) {
log.debug("Entering validateForRequiredFields");
}
List<String> missingFields = new ArrayList<String>();
try {
if (requiredFields != null) {
for (String requiredField : requiredFields) {
if (ifObjectExists(jsonObject, requiredField)) {
if (StringUtils.isEmpty(jsonObject.getString(requiredField))) {
missingFields.add(requiredField);
}
} else {
missingFields.add(requiredField);
}
}
}
if (missingFields != null && missingFields.size() > 0) {
throw new Exception(missingFields);
}
} catch (JSONException e) {
throw new ParserException("Error occured in validateRequiredFields", e);
}
}