Here I have a Rest Controller
#RequestMapping(value = "/mobileNumber", method = RequestMethod.POST, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<ResponseBack> sentResponse() {
return new ResponseEntity<ResponseBack>(ResponseBack.LOGIN_SUCCESS, HttpStatus.ACCEPTED);
}
My Enum Class
public enum ResponseBack {
LOGIN_SUCCESS(0, " success"), LOGIN_FAILURE(1, " failure");
private long id;
private final String message;
// Enum constructor
ResponseBack(long id, String message) {
this.id = id;
this.message = message;
}
public long getId() {
return id;
}
public String getMessage() {
return message;
}
}
When I get the response back from the controller I am getting it as
"LOGIN_SUCCESS"
What I require is
{
"id": "0",
"message": "success"
}
How can I deserialize it to Json and send response, is there any annotation for it.
Please help, thanks.
You must use JsonFormat annotation
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ResponseBack {
...
So you tell that the Json representation of this enum will be the whole object. If you want a specific field to be returned (for example message field) you can annotate the method with JsonValue annotation
#JsonValue
public String getMessage() {
return message;
}
Related
I am creating API with Spring webflux to measure the response time as compare to Spring MVC which has same code.
In Spring MVC, I send response with ResponseEntity<HttpResponse> .
public class HttpResponse {
private Date timestamp = new Date();
private int status;
private boolean error;
private String message;
private Object data;
public Date getTimestamp() {
return timestamp;
}
public int getStatus() {
return status;
}
public boolean isError() {
return error;
}
public String getMessage() {
return message;
}
public Object getData() {
return data;
}
public HttpResponse() {
super();
}
public HttpResponse(int status, boolean error, String message, Object data) {
super();
this.status = status;
this.error = error;
this.message = message;
this.data = data;
}
}
And this is my return statement in requestMapping method:
return new ResponseEntity<HttpResponse>(new HttpResponse(httpStatus.value(), error, message, responseObject), httpStatus);
httpStatus is instance of HttpStatus
error is a boolean
message is a String
responseObject is a Object
This works fine, I get proper response.
In Spring webflux, I have used Mono<ResponseEntity<HttpResponse>> instead of ResponseEntity<HttpResponse>
and this is the return statement in requestMapping method.
return Mono.just(new ResponseEntity<HttpResponse>(new HttpResponse(httpStatus.value(), error, message, responseObj), httpStatus));
this gives this response
{
"timestamp": "2018-06-25T16:18:09.949+0000",
"status": 200,
"error": false,
"message": "23",
"data": {
"scanAvailable": true
}
}
I have passed a Mono in responseObj
Spring WebFlux will only resolve top level Publishers - it is up to you to create such a pipeline.
In your case, you should have something like:
Mono<User> user = …
Mono<ResponseEntity> response = user.map(u -> new ResponseEntity(new HttpResponse(…, u));
return response;
I am using Jackson library to try and parse my JSON file. My JSON is actually an ARRAY of JSON Objects:
JSON ARRAY:
[
{
"Id" : "0",
"name" : "John"
},
{
"Id" : "1",
"name" : "Doe"
}
]
POJO CLASS:
#JsonIgnoreProperties(ignoreUnknown = true)
public class QuestData {
private String Id;
private String name;
public String getId() {
return Id;
}
public String getName() {
return name;
}
}
PARSING JSON:
private void parseJSON(File jsonFile) {
try {
byte[] jsonData = Files.readAllBytes(jsonFile.toPath());
System.out.println(new String(jsonData));
ObjectMapper mapper = new ObjectMapper();
List<QuestData> questDataList = mapper.readValue(jsonData, mapper.getTypeFactory().constructCollectionType(List.class, QuestData.class));
System.out.println("Read values: " + questDataList.get(0).getId());
} catch (IOException e) {
e.printStackTrace();
}
}
My first print statement prints correct Json data back (as String).
But next print statement says NULL. I even tried to itreate over entire list ot see if there is something that is not null, but with no luck.
I do not know what I am doing wrong here.
Jackson will by default use setter methods to set fields. So add setters like:
#JsonProperty("Id") // otherwise Jackson expects id for setId
public void setId(String id) {
Id = id;
}
Alternatively, tell Jackson to look for fields with this config:
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
In this case Jackson will match the name of the field in the class Id with the one in JSON Id
Just add the #JsonProperty annotation to the Id property in your QuestData class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class QuestData {
#JsonProperty("Id")
private String Id;
private String name;
public String getId() {
return Id;
}
public String getName() {
return name;
}
}
(NOTE: I am sorry if the layout of this post isn't the best, I've
spent quite a lot of time figuring the features of this editor)
Hi, I am doing a RESTful web project and I run into a problem returning an object that contains another object (But the object inside is literally an "Object").
In my case I have a Company, Customer and Coupon resources. Each one of then contains fields, #XMLRootElement annotation in the class level, an empty constructor (along with constructors that receives the arguments) and of course, the getters and setters.
As for the service, there are annotations in the class level:
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
And the get method it's self:
#GET
#Path("/myCompany)
public Message getMyCompany(){
Message message;
try{
message = new MessageSuccess(company);
} catch(Exception e){
message = new MessageError(e.getMessage());
}
return message;
}
Now the way Message object is built, it's an abstract class (that contains the #XMLRootElement as well) it has three fields:
messageType (enum)
value (Object)
message (String)
it has all the features of the resource (getters and setters, construction, etc...)
And there are two classes that extending the Message.
they aswell have an empty constructor and parameterized one, they don't have the #XMLRootElement annotations.
Now the problem is, when ever the client does the get method, it receives a JSON object that has
messageType: 'SUCCESS'
value: 'com.publicCodes.resources.Company#6c4sad546d'
Basically it returns a toString() of the Company object.
I have no clue how to fix that.
Returning servlet's Response object is not an option due to a bad practice.
Returning the Company object it's self is as well not an option.
Thanks and waiting for your solutions!
**
EDIT for those who wanna see the actual code:
**
Here is the Message abstract class:
package com.publicCouponRest.util;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement
public abstract class Message {
private MessageResultType messageType;
private Object value;
private String message;
public Message() {
}
public Message(MessageResultType messageType, String message) {
this.messageType = messageType;
this.message = message;
}
public Message(MessageResultType messageType, Object value) {
this.messageType = messageType;
this.value = value;
}
public MessageResultType getMessageType() {
return messageType;
}
public void setMessageType(MessageResultType messageType) {
this.messageType = messageType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And here is MessageSuccess that extends Message:
package com.publicCouponRest.util;
public class MessageSuccess extends Message {
public MessageSuccess() {
}
public MessageSuccess(Object value) {
super(MessageResultType.SUCCESS, value);
}
}
and of course Company resource:
package com.publicCodes.resources;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import com.publicCouponRest.services.AttributeKeys;
#XmlRootElement
public class Company {
private long id;
private String compName;
private String password;
private String email;
private Map<Long, Coupon> coupons;
private CompanyStatus companyStatus;
private AttributeKeys userType = AttributeKeys.COMPANY;
public Company(long id, String compName, String password, String email, Map<Long, Coupon> coupons, CompanyStatus companyStatus) {
this(compName, password, email);
this.id = id;
this.coupons = coupons;
this.companyStatus = companyStatus;
}
public Company(String compName, String password, String email) {
super();
this.compName = compName;
this.password = password;
this.email = email;
}
public Company() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCompName() {
return compName;
}
public void setCompName(String compName) {
this.compName = compName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<Long, Coupon> getCoupons() {
return coupons;
}
public CompanyStatus getCompanyStatus() {
return companyStatus;
}
public void setCompanyStatus(CompanyStatus companyStatus) {
this.companyStatus = companyStatus;
}
public void setCoupons(Map<Long, Coupon> coupons) {
this.coupons = coupons;
}
public AttributeKeys getUserType() {
return userType;
}
public void setUserType(AttributeKeys userType) {
this.userType = userType;
}
}
Ok. I think that you are having too much fun with jackson:
You are trying to put 'whatever object' in a node. aren't you?
To do that you must use the annotation:
#XmlAnyElement(lax=false)
so something like:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public abstract class Message {
....
#XmlAnyElement(lax=false)
private Object value;
....
Should be necessary. This way you will be able to put whatever incoming XML data node in that Object (JAXB will have to know the class of that Object and that class must be annotated, but it let you manage an undetermined class)
Also (EDITED):
In the other way: Object-> XML: The problem now is that you are sending to JAXB your 'Company' object but it only sees an 'Object' because you are telling it that it's an object of type 'Object', and JAXB only know how to serialize an 'Object.class' calling to it's .toString() because Object.class hasn't got any JAXB annotation. Try returning, instead of the object, the result of this method:
(Data will be your response and clazz Company.class or whatever)
import javax.xml.bind.JAXBContext;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
...
public static Element marshallToElement(Object data, Class clazz) {
DOMResult res = null;
try {
JAXBContext ctx = JAXBContextManager.getInstance(clazz.getPackage().getName());
Marshaller marshaller = ctx.createMarshaller();
res = new DOMResult();
marshaller.marshal(data, res);
} catch (JAXBException e) {
LOG.error(e);
}
return ((Document)res.getNode()).getDocumentElement();
}
This way you will return a JAXBElement, which is a 'bunch of nodes' that JAXB will know how to marshall.
At this point, if it works for you, it's a good practice caching the JAXBContext, it can be do saffely (JAXBContext is thread-safe, Marshallers NO) and it's a heavy duty for JAXB to execute that:
JAXBContextManager.getInstance(clazz.getPackage().getName())
So try to do it only once for each transformation.
PS:
Try putting JAXB annotations only in final classes, I'd had problems with that (because I was using annotations in an annotated subclass... And finally is cleaner to have all annotations in the same class)
Jersey/JAX-RS 2 client
I consider you read a bit of WebTarget API, how it works and what it returns. And Also return a Response Object
And then you can change your method to this:
#GET
#Path("/myCompany)
public Response getMyCompany() {
Message message;
try {
message = new MessageSuccess(company);
return Response.status(200).entity(message).build();
} catch (Exception e) {
message = new MessageError(e.getMessage());
return Response.status(500).entity(message).build();
}
}
After that you should add this to your main method:
WebTarget target = client.target(BASE).path("myCompany");
Response response = target.request().accept(...).post(Entity.json(message));//modify this line to suit your needs
Message message = response.readEntity(Message.class);
Have tried similar thing before and I got my help from #peeskillet's answer on this stackoverflow page.
Hope it did be of Help,thank you.
I built a REST API Service using Java Spring Cloud / Boot. Firstly, I made a simple class connected to a MongoDB and a controller with service that should allow me to add, delete, update and get all the objects. When using POSTMAN these all work, however when I want to add or update an object using redux and fetch API I get a status 400 and "bad request" error. This seems to have something to do with the JSON I'm sending in the body but it is the exact same format of JSON that is working with for example POSTMAN.
My action in Redux. For simplicity / test purposes I added an object at the top in stead of using the object being sent from the page.
var assetObject = {
"vendor" : "why dis no work?",
"name": "wtf",
"version": "231",
"category" : "qsd",
"technology" : "whatever"
}
export function addAsset(access_token, asset) {
return dispatch => {
fetch(constants.SERVER_ADDRESS + '/as/asset/add',
{
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer' + access_token,
'Content-Type': 'application/json'
},
body: assetObject
})
.then(res => dispatch({
type: constants.ADD_ASSET,
asset
}))
}
}
Controller code in Java Spring:
#RequestMapping(method = RequestMethod.POST, path = "/add")
public void addAsset(#RequestBody Asset asset) {
assetService.addAsset(asset);
}
Status ok while doing it in postman:
The error I get when using Redux / Fetch API (I only removed the directory structure because it has company name in it):
Have been stuck on this for a while, any help is much appreciated!
EDIT Asset Object:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "assets")
public class Asset {
#Id
private String id;
private String vendor;
private String name;
private String version;
private String category;
private String technology;
public Asset() {
}
public Asset(String id,
String vendor,
String name,
String version,
String category,
String technology) {
this.id = id;
this.vendor = vendor;
this.name = name;
this.version = version;
this.category = category;
this.technology = technology;
}
public String getId() {
return id;
}
public String getVendor() {
return vendor;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getTechnology() {
return technology;
}
public void setId(String id) {
this.id = id;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public void setCategory(String category) {
this.category = category;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
your error message says :
; required request body is missing
i think the error happens when your controller method
trying to form an object from the incoming request.
when you are sending the request you have to set each and every field related to the object.
if you are planning on not setting a property you should mark that field with #JsonIgnore annotation.
you can use #JsonIgnore annotation on the variable which will ignore this property
when forming the object as well as when outputing the object.
use #JsonIgnore annotation on the setter method , which i think you should do now since
you are ignoring the id property when making the request.
#JsonIgnore
public void setId(String id) {
this.id = id;
}
and you can return httpstatus code from the controller method,
so that client knows request was successful
#ResponseBody
public ResponseEntity<String> addAsset(#RequestBody Asset asset) {
return new ResponseEntity<String>("your response here", HttpStatus.OK);
}
I am having a problem marshalling a RequestBody when the parent class has a namespace.
Class:
#XmlRootElement(name = "blah")
public class Test {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
XML:
<blah>
<id>23333</id>
</blah>
Code:
#RequestMapping( value = "/blah", method = RequestMethod.POST, consumes = { MediaType.TEXT_XML_VALUE }, produces = { MediaType.TEXT_XML_VALUE})
public String getBlah( #RequestBody Test request ) throws Exception
{
assert(null != request.getId());
return "blah";
}
This works fine. However, if I use #XmlRootElement(name = "blah", namespace="home") on the class, and <blah xmlns="home"> in the request, the Test class constructs, but it's ID value is never set.
I'm at a loss.
Before public void setId method add annotation #XmlElement