Setting up an Java Postman call assigning values to the variables but its shows null.
#PostMapping("/caStudents/student")
public String generateSignedValue(#RequestBody StudentRequest studentRequest) throws Exception
String signedValue=studentService.getSignedValue(studentRequest);
return signedValue;
My Pojo Student Class
public class StudentRequest {
String user;
Long duration ;
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
Postman Request
{"studentRequest":[{"user":"admin","duration":19336}]}
your request body should be like this:
{"user":"admin","duration":19336}
because you are getting StudentRequest as RequestBody and it means you should send StudentRequest internal properties not containing StudentRequest it self in request ,
second problem is that your RequestBody contains singular object not array .
According to what you've given us your request should actually be
{
"user": "admin",
"duration": 19336
}
If you want to provide multiple student requests at once (within an array), then you're StudenRequest class should look somewhat like this:
public class StudentRequest {
List<StudentR>;
// Getter and Setter or not in case you use lombok
class StudenR {
String user;
Long duration ;
}
}
Related
I'm sending a post request from the client to the server. The body of the post request looks like this:
...
body: JSON.stringify
({
command: 'someString',
dataFields: setDataList()
})
...
while the "setDataList()" returns the following structure:
[ {…}, {…}, {…}, ..., {…} ]
[0: {type: "_header_", label: "upload"}
1: {type: "_image_", name: "data:image/jpeg;base64", value: "base64 encoded string", label: "someImage.JPG"}
2: {...}]
I'm having issues processing the content of the "dataFields" key at the server. Currently, the SpringBoot applicaiton looks like this:
#PostMapping(
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public void postBody(#RequestBody ManageRequest manageRequest) {
...
}
and "ManageRequest" like this:
import java.util.List;
public class ManageRequest {
private String accountId;
private String command;
private String transactionId;
private List<String> dataFields;
public String getAccountId() {
return accountId;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public List<String> getDataFieldList() {
return dataFields;
}
public void setDataFieldList(List<String> dataList) {
this.dataFields = dataList;
}
}
I'm not experienced in handling such requests with Java. My goal would be to extract the content of the "dataFields" like this: "dataFields[0], dataFields[1], ..." and allocate them to a new List to add to a post request.
At the moment, the list seems to be empty when arriving at the end point.
Your problems is with the List.
The server is waiting for a List of Strings but you are sending a List of objects with fields that are Strings.
private List<String> dataFields; // This property is a List of string not a list of "dataFields"
You should create a class DataField and it would looks like this
public class DataField{
private String type;
private String label;
private String name;
.
.
.
}
And then in your ManageRequest class you should do like this:
public class ManageRequest {
private String accountId;
private String command;
private String transactionId;
private List<DataField> dataFields;
//Getter and setters
}
I'm using Restet and I wanted to know if its possible if a ServerResource entity type is set, for example for this type of entity:
#XStreamAlias("role")
#ApiModel
public class Role {
private String entityId;
private String name;
#ApiModelProperty(required = false, value = "")
private List<String> aclRead;
#ApiModelProperty(required = false, value = "")
private List<String> acLWrite;
#ApiModelProperty(required = false, value = "")
private Boolean publicRead;
#ApiModelProperty(required = false, value = "")
private Boolean publicWrite;
public String getEntityId() {
return entityId;
}
public void setEntityId(String entityId) {
this.entityId = entityId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAclRead() {
return aclRead;
}
public void setAclRead(List<String> aclRead) {
this.aclRead = aclRead;
}
public List<String> getAcLWrite() {
return acLWrite;
}
public void setAcLWrite(List<String> acLWrite) {
this.acLWrite = acLWrite;
}
public Boolean getPublicRead() {
return publicRead;
}
public void setPublicRead(Boolean publicRead) {
this.publicRead = publicRead;
}
public Boolean getPublicWrite() {
return publicWrite;
}
public void setPublicWrite(Boolean publicWrite) {
this.publicWrite = publicWrite;
}
}
How can we be able to POST without the need of passing all the fields, for this example we only wanted to pass the "name" from the Client Request, but doing that throws 415 - Unsupported Media Type
In our client we only do pass this JSON
{
"role" : {
"name" : "AdminRole"
}
}
For the Get response of the Resource, the return type is Role also so the client will get all the fields, entityId, name, aclRead, aclWrite, publicRead and publicWrite through the Restlet marshalling.
The problem we have is that we cannot POST.
In the post request, the json data should only consist of the the entity parameters without the entity name as root key. So, your post request should look like this:
{
"name" : "AdminRole"
}
I am creating simple rest client in Java/Spring. My request has been consumed properly by remote service and I got the response String something:
{"access_token":"d1c9ae1b-bf21-4b87-89be-262f6","token_type":"bearer","expires_in":43199,"grant_type":"client_credentials"}
The code below is the Object where I want to bind values from Json Response
package Zadanie2.Zadanie2;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Token {
String access_token;
String token_type;
int expiresIn;
String grantType;
//////////////////////////////////////////////////////
public Token() {
/////////////////////////////////
}
/////////////////////////////////////////////////////
public void setAccessToken(String access_token) {
this.access_token=access_token;
}
public String getAccessToken() {
return access_token;
}
////////////////////////////////////////////////
public void setTokenType(String token_type) {
this.token_type=token_type;
}
public String getTokenType() {
return token_type;
}
//////////////////////////////////////////////////////
public void setExpiresIn(int expiresIn) {
this.expiresIn=expiresIn;
}
public int getExpiresIn() {
return expiresIn;
}
//////////////////////////////////////////////////////////
public void setGrantType(String grantType) {
this.grantType=grantType;
}
public String getGrantType() {
return grantType;
}
}
all the time I am getting "unrecognized field access_token" but when I add objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
then access_token will be null
jsonAnswer=template.postForObject(baseUriAuthorize, requestEntity, String.class);
System.out.println(jsonAnswer);
Token token=objectMapper.readValue(jsonAnswer, Token.class);
System.out.println(token.getAccessToken());
I tried with #JsonProperty annotations. I tried with changing field by for example "#JsonProperty(accessToken)" because I thought there is an issue with "_" sign in variable name. I added getters and setters. Maybe there is a problem with the version I use but I don't think so because I am using "com.fasterxml.jackson.core"
You tried with "#JsonProperty(accessToken)". But your json contains access_token. how it works?
Try with this class:
public class Token {
#JsonProperty("access_token")
String accessToken;
#JsonProperty("token_type")
String tokenType;
int expiresIn;
String grantType;
//getter setter
}
Your setters do not match with the JSON key.
To read it correctly, you should change your setters to:
setAccess_token()
setToken_type()
...
But honestly, this is so ugly.
Try following the Java bean name convention and customize the JSON key with #JsonProperty:
public class Token {
#JsonProperty("access_token")
String accessToken;
....
}
I have the following JSON to represent the server response for a salt request:
{
"USER":
{
"E_MAIL":"email",
"SALT":"salt"
},
"CODE":"010"
}
And i tried to map it with the following POJO:
public class SaltPOJO {
private String code = null;
private User user = null;
#Override
public String toString() {
return this.user.toString();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public class User {
private String e_mail = null;
private String salt = null;
#Override
public String toString() {
return this.e_mail + ": " + this.salt;
}
public String getE_mail() {
return e_mail;
}
public void setE_mail(String e_mail) {
this.e_mail = e_mail;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
}
Now everytime i do this:
Gson gson = new Gson();
SaltPOJO saltPojo = gson.fromJson(json.toString(), SaltPOJO.class);
Log.v("Bla", saltPojo.toString());
The saltPojo.toString() is null. How can i map my JSON into POJO using Gson?
Is the order of my variables important for the Gson mapping?
Is the order of my variables important for the Gson mapping?
No, that's not the case.
How can i map my JSON into POJO using Gson?
It's Case Sensitive and the keys in JSON string should be same as variable names used in POJO class.
You can use #SerializedName annotation to use any variable name as your like.
Sample code:
class SaltPOJO {
#SerializedName("CODE")
private String code = null;
#SerializedName("USER")
private User user = null;
...
class User {
#SerializedName("E_MAIL")
private String e_mail = null;
#SerializedName("SALT")
private String salt = null;
You don't have proper mapping between your getter and setter. If you change your json to something like below, it would work:
{
"user":
{
"email":"email",
"salt":"salt"
},
"code":"010"
}
If you are getting json form third party then unfortunately, you would have to change your pojo or you could use adapter.
I am trying to show DB data to my webpage.
I have made following code when GET request to the #RequestMapping(value = "/api/binder").
but when get request came to this method it will fetch data (I have print on console and display well) but it doesn't map to my Java Script Ajax call, it's showing me an error.
Following is my code for to fetch data :
#Autowired
IBinderViewRepository repository;
#RequestMapping(method= RequestMethod.GET)
public #ResponseBody
List<BinderResponse> getBinders(){
List<BinderView> binders = repository.getBinders();
List<BinderResponse> responses = new ArrayList<>();
ModelMapper mapper = Mapper.getInstance();
for(int i = 0; i < binders.size(); i++){
System.out.println("In Loop");
BinderResponse response = mapper.map(binders.get(i),BinderResponse.class);
System.out.println("Data :: " + response.getBinderName());
responses.add(response);
}
return responses;
}
but it shows me following error :
HTTP Status 500 - Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])
Here is ajax call from knockout js :
ajax.get('api/binder').done(function(response){ ... }
Here BinderView and BinderResponse have same fields :
private String binderName;
private String binderAddress1;
and getter setter as well in both.
and repository.genBinders() method bring data from DB.
Here is insert method and works fine for me :
#RequestMapping(method= RequestMethod.POST,consumes = "application/json")
public #ResponseBody
IWebApiResponse addBinder(#RequestBody AddBinderForm binder){
.....
}
Shall I have to put any json annotation on my BinderResponse class ?
I don't understand where am i wrong ?Anyone pleas guide me.
UPDATE :
public class BinderResponse extends WebApiResponseBase {
private String binderName;
private String binderAddress1;
public String getBinderName() {
return binderName;
}
public void setBinderName(String binderName) {
this.binderName = binderName;
}
public String getBinderAddress1() {
return binderAddress1;
}
public void setBinderAddress1(String binderAddress1) {
this.binderAddress1 = binderAddress1;
}
}
BinderView :
public class BinderView extends BaseView {
private String binderName;
private String binderAddress1;
public String getBinderName() {
return binderName;
}
public void setBinderName(String binderName) {
this.binderName = binderName;
}
public String getBinderAddress1() {
return binderAddress1;
}
public void setBinderAddress1(String binderAddress1) {
this.binderAddress1 = binderAddress1;
}
}
In console it prints data / BinderName :
In Loop
Data :: ada
In Loop
Data :: tya
New Update :
Here is BaseView :
#MappedSuperclass
public abstract class BaseView implements IEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="id")
private long id;
public long getId() {
return id;
}
public void setId(long id) {
if (this.id != 0 && this.id != id) {
throw new IllegalStateException(
"The ID must not be changed after it is set.");
}
this.id = id;
}
}
and In IEntity :
public interface IEntity extends Serializable {
long getId();
void setId(long id);
}
WebApiResponseBase :
public class WebApiResponseBase implements IWebApiResponse {
private String _uri;
#Override
public String getUri() {
return _uri == null ? "" : _uri;
}
#Override
public void setUri(String uri) {
_uri = uri;
}
}
Jackson, by default, serializes an object's whole inheritance hierarchy, ie. the parent class fields as well. In the case of
public class BinderResponse extends WebApiResponseBase {
it seems like
Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])
Jackson tries to serialize a field called valid from a getter called isValid (which is a conventional bean property name). The getter method, however, seems to throw a NullPointerException for whatever reason.
If you want Jackson to ignore it, you can annotate the getter with #JsonIgnore or your class with #JsonIgnoreProperties and specify the property name, ie. valid.
In my case when I used #JsonIgnore the exception has been gone but the problem was it couldn't receive that value from API Request anymore and Spring ignored it (obviously because of #JsonIgnore) So I investigated about the issue and figured out that the problem was the getter and setter.
I had the Integer property while my getter was int. So when I changed the getter to Integer my problem solved and error's gone.
private Integer purchaseId;
#JsonIgnore
public int getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(int purchaseId) {
this.purchaseId = purchaseId;
}
Changed to :
private Integer purchaseId;
public Integer getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(Integer purchaseId) {
this.purchaseId = purchaseId;
}
#Column(name="createddate")
private Date createdDate;
#Transient
private String formatedCreatedDate;
public String getFormatedCreatedDate() {
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
return dateFormat.format(this.getCreatedDate());
}
It throws the same exception because here may be null by calling getCreatedDate() value come so it can't format null date so keep null check here like:
Solution
public String getFormatedCreatedDate() {
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date createDdate=this.getCreatedDate();
if(createDdate!=null){
return dateFormat.format(createDdate);
}
return "-";
}