How to ignore as well as edit properties for JSON objects in Jersey Rest

As part of my requirement, I am looking at a web service that uses the Employee class to input in JSON format. The class of employees is as follows. If you see that there are 3 properties inside the class, such as status, password, createTime. Now I'm trying to prevent the user from providing properties such as status and creationTime. I want to say that I do not want to allow the user to enter JSON as: -

{ "emp_id": " xyz@gmail.com ", "credentials" : {"password": "xxxxx"}, "status": "ACTIVE", "creationTime": "<UTC time>" } 

When the status and creation time are entered, this should lead to the 400 error message. Similarly, when I return the result back to the user, for example, return Response.status(Status.ACCEPTED).entity(employee).build(); , it should not display createTime or credentials. It should look like this: -

  { "emp_id": " xyz@gmail.com ", "status": "ACTIVE", } 

I could see that there is a @JsonIgnore property that does not work in my case for status. I tried Jackson.

My Employee class is as follows:

 import java.util.Date; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonProperty; @XmlRootElement public class Employee { @XmlElement(name = "emp_id", required = true) @JsonProperty("emp_id") private String empId; private Credentials credentials; private String status; private Date creationTime; public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public Credentials getCredentials() { return credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } @JsonIgnore public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCreationTime() { return creationTime; } public void setCreationTime(Date creationTime) { this.creationTime = creationTime; } } 
+6
source share
4 answers

Default JSON Provider Default Jersey

From Jersey Documentation :

Support for JSON binding through MOXy is the standard and preferred way to support JSON binding in your Jersey 2.0 applications. When the MOXy JSON module is on its way to classes, Jersey will automatically detect the module and will enable JSON binding via MOXy in your applications without any problems.

Since MOXy supports JAXB annotations , try using @XmlTransient . He has to do the trick.

Using Jackson as a JSON Provider

To use Jackson 2.x as your JSON provider, you need to add jersey-media-json-jackson to your pom.xml file:

 <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.22.1</version> </dependency> 

To use Jackson 1.x, you will need the jersey-media-json-jackson1 :

 <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson1</artifactId> <version>2.22.1</version> </dependency> 

For more information about dependencies, see the Jersey documentation .

If you can, select Jackson 2.x over Jackson 1.x.

Register Jackson as a JSON Provider

To use Jackson as your JSON provider, you need to register JacksonFeature for Jackson 2.x (or Jackson1Feature for Jackson 1.x) in the ResourceConfig class (Jersey native implementation of the Application class):

 public class MyApplication extends ResourceConfig { public MyApplication() { register(JacksonFeature.class); } } 

See the documentation for more details.

Choosing the Right JsonProperty Annotation

Make sure you use the correct JsonProperty annotation according to Jackson's version:

Read more about annotations in the documentation:

Try annotating your field

Alternatively, instead of annotating the getStatus() method, try annotating the status field using the corresponding @JsonProperty annotation.

+1
source

whenever your leisure web service uses this json object, it will convert it to a POJO object. If your JSON object does not contain some fields that are in the POJO object, then these values ​​will be initialized to NULL.

Now you can give 404 answers accordingly by checking the null values.

0
source

First of all, check that you are using the Json / XML parser. Jersey uses Moxy by default, so replace Moxy with Jackson as the @JsonIgnore you use is Jackson's annotation.

Add the dependencies below to enable the Jackson parser for Json and XML.

 <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-xml-provider</artifactId> <version>2.5.4</version> </dependency> 

Jersey has an automatic detection mechanism that Jackson should automatically register, if that fails, use the class below.

 public class ResourceConfig extends org.glassfish.jersey.server.ResourceConfig { public ResourceConfig() { super(); registerJacksonProvider(); packages("com.rest"); } /** * Custom provider to handle JSON and XML request */ private void registerJacksonProvider() { ObjectMapper mapper = new ObjectMapper(); XmlMapper xmlMapper = new XmlMapper(); xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.enable(SerializationFeature.INDENT_OUTPUT); JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); JacksonJaxbXMLProvider xmlProvider = new JacksonJaxbXMLProvider(); provider.setMapper(mapper); xmlProvider.setMapper(xmlMapper); register(provider); register(xmlProvider); } } 

To disable Moxy, add a class below.

 import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.CommonProperties; import org.glassfish.jersey.server.ServerProperties; @Provider public class DisableMoxyFeature implements Feature { @Override public boolean configure(final FeatureContext context) { final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.' + context.getConfiguration().getRuntimeType().name().toLowerCase(); context.property(disableMoxy, true); context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true); context.property(ServerProperties.MOXY_JSON_FEATURE_DISABLE, true); return true; } } 
0
source

When creating a json response object from an employee object using JSON-Lib, you can pass jsonconfig, which can exclude certain properties, or you can also set the json properties filter for this configuration, as shown below

 JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if ("credentials".equals(name) || "creationTime".equals(name)) { return true; } return false; } }); 

OR

 JsonConfig config = new JsonConfig(); List<String> excludes = new ArrayList<String>(); excludes.add("credentials"); excludes.add("creationTime"); JSONObject.fromObject(response, jsonConfig); 

In the first part of your question, you can very well use the json scheme and check the resulting json object before processing

 JSONSchemaValidator.validate(jsonBody, <path_of_your_schema_file>); JSONObject jsonObj = JSONObject.fromObject(jsonBody); 
0
source

All Articles