How to make input attributes required in post body request? - java

Here is my example:
Java:
#JsonProperty("id")
private String id;
#JsonProperty(value = "name", required = true)
private String deviceName;
I made the name as a required field. In request how to make it as required field. I should send the name value from request.
But when I enter this:
{ "id": "abc123",}
It should send error response back.
Please help me.

Jacksons JsonProperty Annotation is not used for Validation. see: Jackson #JsonProperty(required=true) doesn't throw an exception. But you can use Bean Validation, e.g.:
class Device {
#JsonProperty("id")
private String id;
#NotEmpty
#JsonProperty(value = "name")
private String deviceName;
}

Related

Change tag name in SOAP xml response (field in class and tag in response must be different)

I have class like this:
#Root(name = "address_v1", strict = false)
public class AddressItem {
#Attribute(name = "idAddress")
private Long addressId;
#Attribute(name = "idClient")
private Long clientId;
...
}
And I have response:
...
<ax23:address xsi:type="ax24:AddressItem">
<ax24:addressId>1111</ax24:addressId>
<ax24:clientId>1109</ax24:clientId>
...
But I need:
<ax23:address xsi:type="ax24:AddressItem">
<ax24:idAddress>1111</ax24:idAddress>
<ax24:idClient>1109</ax24:idClient>
Annotation #Attribute(name = "idAddress") doesn't work. (org.simpleframework.xml.Attribute).
I use wsdl2java as wsdl creator.
try with following steps and modify your POJO class as given below,
use #Element annotation for XML Element instead of #Attribute annotation (please refer to documentation for more info)
The Element annotation is used to represent a field or method that
appears as an XML element.
set the relevant xml element names to #Root and #Element annotations
AddressItem.java
#Root(name = "ax23:address", strict = false)
public class AddressItem {
#Element(name = "ax24:addressId")
private Long addressId;
#Element(name = "ax24:clientId")
private Long clientId;
...
}

How to access the String json payload and mapping it to an Object in Spring rest controller?

I'm building a rest API using Spring Boot rest services.
I have a Java class:
class Person{
int id;
#notNull
String name;
#notNull
String password;
}
And I want to make an API to create a Person object. I will recieve a POST request with json body like:
{
"name":"Ahmad",
"password":"myPass",
"shouldSendEmail":1
}
As you can see there are an extra field "shouldSendEmail" that I have to use it to know if should I send an email or not after I create the Person Object.
I am using the following API:
#RequestMapping(value = "/AddPerson", method = RequestMethod.POST)
public String savePerson(
#Valid #RequestBody Person person) {
personRepository.insert(person);
// Here I want to know if I should send an email or Not
return "success";
}
Is there a method to access the value of "shouldSendEmail" while I using the autoMapping in this way?
There's many options for you solve. Since you don't want to persist the shouldSendEmail flag and it's ok to add into you domain class, you can use the #Transient annotation to tell JPA to skip the persistence.
#Entity
public class Person {
#Id
private Integer id;
#NotNull
private String name;
#NotNull
private String password;
#Transient
private Boolean shouldSendEmail;
}
If you want more flexible entity personalizations, I recommend using DTO`s.
MapStruct is a good library to handle DTO`s
You will need an intermediary DTO, or you will otherwise have to modify person to include a field for shouldSendEmail. If that is not possible, the only other alternative is to use JsonNode and manually select the properties from the tree.
For example,
#Getter
public class PersonDTO {
private final String name;
private final String password;
private final Integer shouldSendEmail;
#JsonCreator
public PersonDTO(
#JsonProperty("name") final String name,
#JsonProperty("password") final String password,
#JsonProperty("shouldSendEmail") final Integer shouldSendEmail
) {
this.name = name;
this.password = password;
this.shouldSendEmail = shouldSendEmail;
}
}
You can use #RequestBody and #RequestParam together as following
.../addPerson?sendEmail=true
So send the “sendEmail” value as request param and person as request body
Spring MVC - Why not able to use #RequestBody and #RequestParam together
You have mutli solutions
1 - You can put #Column(insertable=false, updatable=false) above this property
2 - send it as request param #RequestParam
#RequestMapping(value = "/AddPerson", method = RequestMethod.POST)
public String savePerson(
#Valid #RequestBody Person person, #RequestParam boolean sendMail) {}
3- use DTO lets say PersonModel and map it to Person before save

Custom bean validation

I'm developing an application using spring-boot. I want to validate the user bean using JSR annotation. The problem is that I have some fields that depend on the value of others. For example when status="user_pr" I have to make the address, county, and phoneNumber as mandatory.
this my bean:
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
#NotNull(message = "required")
private String status;
#JsonProperty("first_name")
#NotNull(message = "required")
private String firstName;
#NotNull(message = "required")
private String name;
#NotNull(message = "required")
#Pattern(message = "Email not valid", regexp = "^([\\w\\.\\-_]+)?\\w+#[\\w-_]+(\\.\\w+){1,}$")
private String mailAddress;
private String country;
private String phoneNumber;
#JsonProperty("address")
private Address billingAddress;
}
Would you have any ideas ?
Best regards
I had the same problem a couple of weeks ago, I created my own validation annotation with a custom validation logic. You can find the showcase project in my repository: ConditionalValidator.
If you have any questions, just ask.

Jackson - Deserialize nested JSON

I have a JSON string which will be of the following format:
{
"response": {
"execution_status": "ready",
"report": {
"cache_hit": true,
"created_on": "2013-07-29 08:42:42",
"fact_cache_error": null,
"fact_cache_hit": true,
"header_info": null,
"name": null,
"report_size": "5871",
"row_count": "33",
"url": "report-download?id=278641c223bc4e4d63df9e83d8fcb4e6"
},
"status": "OK"
}
}
The response part of the JSON is common for a bunch of response types. The report part of this JSON holds good only for this response. So I had created a Response class as shown below with getters and setters (have not included the getters and setters here for brevity):
#JsonRootName(value = "response")
public class Response implements Serializable {
private static final long serialVersionUID = -2597493920293381637L;
#JsonProperty(value = "error")
private String error;
#JsonProperty(value = "error_code")
private String errorCode;
#JsonProperty(value = "error_id")
private String errorId;
#JsonProperty(value = "error_description")
private String errorDescription;
#JsonProperty(value = "method")
private String method;
#JsonProperty(value = "service")
private String service;
#JsonProperty(value = "status")
private String status;
#JsonProperty(value = "execution_status")
private String executionStatus;
}
And then, I created a Report class with the fields in the report element as below. The ReportResponse class will extend from the Response class (again the getters and setters are not included for brevity):
public class ReportResponse extends Response {
private static final long serialVersionUID = 4950819240030644407L;
#JsonProperty(value = "cache_hit")
private Boolean cacheHit;
#JsonProperty(value = "created_on")
private Timestamp createdOn;
#JsonProperty(value = "fact_cache_error")
private String factCacheError;
#JsonProperty(value = "fact_cache_hit")
private Boolean factCacheHit;
#JsonProperty(value = "header_info")
private String headerInfo;
#JsonProperty(value = "json_request")
private String jsonRequest;
#JsonProperty(value = "name")
private String name;
#JsonProperty(value = "report_size")
private Integer reportSize;
#JsonProperty(value = "row_count")
private Integer rowCount;
#JsonProperty(value = "url")
private String url;
}
Now when I use the ObjectMapper to map to the ReportResponse object, I get the following error:
String jsonString = "{\"response\": {\"execution_status\": \"ready\", \"report\": {\"cache_hit\": true, \"created_on\": \"2013-07-29 09:53:44\", \"fact_cache_error\": null, \"fact_cache_hit\": false, \"header_info\": null, \"name\": null, \"report_size\": \"5871\", \"row_count\": \"33\", \"url\": \"report-download?id=2ff62c07fc3653b68f2073e7c1aa0517\"}, \"status\": \"OK\"}}";
ObjectMapper mapper = new ObjectMapper();
ReportResponse reportResponse = mapper.readValue(jsonString, ReportResponse.class);
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "report"
I know that I can create a separate Report class and then embed it in the ReportResponse with the #JsonProperty anotation. Is there a way I can avoid that and mark the ReportResponse class with an annotation which would map it to the "report" element in the JSON?
There is no annotation which could handle this case yet. There is a ticket requesting this feature.
Here is a brief statement from one of the owners regarding this topic.
Quote from the mentioned statement:
Tatu Saloranta: "… #JsonProperty does not support transformations, since the data binding is based on incremental parsing and does not have access to full tree representation. Supporting #JsonUnwrapped was non-trivial, but doable; and thus converse ("#JsonWrapped") would be doable, theoretically speaking. Just plenty of work. …"
I see couple of problems in your code. First thing is that you don't have report attribute in your Response class, which is required as per the json structure you have shown. Secondly you need to provide the getters and setters in your bean classes as those will be used by the jackson for marhsalling and unmarshalling of json/object.

Only using #JsonIgnore during serialization, but not deserialization

I have a user object that is sent to and from the server. When I send out the user object, I don't want to send the hashed password to the client. So, I added #JsonIgnore on the password property, but this also blocks it from being deserialized into the password that makes it hard to sign up users when they don't have a password.
How can I only get #JsonIgnore to apply to serialization and not deserialization? I'm using Spring JSONView, so I don't have a ton of control over the ObjectMapper.
Things I've tried:
Add #JsonIgnore to the property
Add #JsonIgnore on the getter method only
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding #JsonIgnore to the getter.
Which you've tried:
Add #JsonIgnore on the getter method only
Do this, and also add a specific #JsonProperty annotation for your JSON "password" field name to the setter method for the password on your object.
More recent versions of Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
Docs can be found here.
In order to accomplish this, all that we need is two annotations:
#JsonIgnore
#JsonProperty
Use #JsonIgnore on the class member and its getter, and #JsonProperty on its setter. A sample illustration would help to do this:
class User {
// More fields here
#JsonIgnore
private String password;
#JsonIgnore
public String getPassword() {
return password;
}
#JsonProperty
public void setPassword(final String password) {
this.password = password;
}
}
Since version 2.6: a more intuitive way is to use the com.fasterxml.jackson.annotation.JsonProperty annotation on the field:
#JsonProperty(access = Access.WRITE_ONLY)
private String myField;
Even if a getter exists, the field value is excluded from serialization.
JavaDoc says:
/**
* Access setting that means that the property may only be written (set)
* for deserialization,
* but will not be read (get) on serialization, that is, the value of the property
* is not included in serialization.
*/
WRITE_ONLY
In case you need it the other way around, just use Access.READ_ONLY.
In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using #RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.
Another easy way to handle this is to use the argument allowSetters=truein the annotation. This will allow the password to be deserialized into your dto but it will not serialize it into a response body that uses contains object.
example:
#JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
String foo;
String bar;
}
Both foo and bar are populated in the object, but only foo is written into a response body.
"user": {
"firstName": "Musa",
"lastName": "Aliyev",
"email": "klaudi2012#gmail.com",
"passwordIn": "98989898", (or encoded version in front if we not using https)
"country": "Azeribaijan",
"phone": "+994707702747"
}
#CrossOrigin(methods=RequestMethod.POST)
#RequestMapping("/public/register")
public #ResponseBody MsgKit registerNewUsert(#RequestBody User u){
root.registerUser(u);
return new MsgKit("registered");
}
#Service
#Transactional
public class RootBsn {
#Autowired UserRepository userRepo;
public void registerUser(User u) throws Exception{
u.setPassword(u.getPasswordIn());
//Generate some salt and setPassword (encoded - salt+password)
User u=userRepo.save(u);
System.out.println("Registration information saved");
}
}
#Entity
#JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String country;
#Column(name="CREATED_BY")
private String createdBy;
private String email;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_LOGIN_DATE")
private Timestamp lastLoginDate;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="MODIFICATION_DATE")
private Timestamp modificationDate;
#Column(name="MODIFIED_BY")
private String modifiedBy;
private String password;
#Transient
private String passwordIn;
private String phone;
#Column(name="RECORD_DATE")
private Timestamp recordDate;
private String salt;
private String status;
#Column(name="USER_STATUS")
private String userStatus;
public User() {
}
// getters and setters
}
You can use #JsonIgnoreProperties at class level and put variables you want to igonre in json in "value" parameter.Worked for me fine.
#JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
private int myVariable1;,
private int myVariable2;
}
You can also do like:
#JsonIgnore
#JsonProperty(access = Access.WRITE_ONLY)
private String password;
It's worked for me
I was looking for something similar. I still wanted my property serialized but wanted to alter the value using a different getter. In the below example, I'm deserializing the real password but serializing to a masked password. Here's how to do it:
public class User() {
private static final String PASSWORD_MASK = "*********";
#JsonIgnore
private String password;
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public String setPassword(String password) {
if (!password.equals(PASSWORD_MASK) {
this.password = password;
}
}
public String getPassword() {
return password;
}
#JsonProperty("password")
public String getPasswordMasked() {
return PASSWORD_MASK;
}
}
The ideal solution would be to use DTO (data transfer object)

Categories