A Rest service is mapped on one url with some #RequestBody where i am mapping json to pojo. Pojo contains nested classes following is sample code.
#RequestMapping(value = "/saveExampleObject.html", method = RequestMethod.POST)
public #ResponseBody List<String> saveExampleObjectDefintion(#RequestBody ExampleObject exampleObject) throws DataAccessException,DataNotPersistException {
List<String> msg = saveService.save(exampleObject);
return msg;
}
and the object is like
class ExampleObject{
String name;
SubClass subClass;
.....
}
and json is
{
"name":"name",
"subClass":{
.....
}
I have configured spring mvc annotation and conversion is also happening.
But some fields are null. I cross checked names of null field they are same as in json and pojo.
P.S. Only first fields are getting values in subclass.Thanks.
in your json you have subClass but in your class you have subclass... is case sensitive
Here the setters were not defined properly and hence there was an error. Spring MVC uses the setters to properly convert POJO to JSON and vice versa.
Related
I'm using Jackson in my Spring Boot application.
I want to convert request parameters to POJO.
But when I use #ModelAttribute with #JsonAlias, it doesn't work.
Request POJO
#Data
public RequestPojo {
#JsonAlias( "FOO_SNAKE" ) // Not working
private String fooCamelAlias;
}
Controller:
#GetMapping("/foo")
public void getFoo( #ModelAttribute RequestPojo requestPojo ) {
...
}
Request:
(1) http://localhost?FOO_SNAKE=Foo_snake
(2) http://localhost?fooCamelAlias=Foo_snake
fooCamelAlias is null when I request with (1).
But (2) works.
#JsonAlias will not work with #ModelAttribute because #ModelAttribute is used for binding data for request param (in key value pairs). If you want to do JSON mapping then better to use #RequestBody
I'm using Spring FeignClient to access a RESTful endpoint, the endpoint returns an xml,
I want to get the response as a JSON, which in turn will map to a POJO.
1) When I access the endpoint on the browser, I get response as below,
<ns3:Products xmlns:ns2="http://schemas.com/rest/core/v1" xmlns:ns3="http://schemas/prod/v1">
<ProductDetails>
<ProdId>1234</ProdId>
<ProdName>Some Text</ProdName>
</ProductDetails>
</ns3:Products>
2) #FeignClient(value = "productApi", url = "http://prodservice/resources/prod/v1")
public interface ProductApi {
#GetMapping(value="/products/{productId}", produces = "application/json")
ProductDetails getProductDetails(#PathVariable("productId") String productId)
// where, /products/{productId} refers the RESTful endpoint
// by mentioning, produces = "application/json", I believe the response xml would be converted to JSON Java POJO.
3) POJO
public class ProductDetails {
private String ProdId;
private String ProdName;
//...setters & getters
}
4) Service Layer
ProductDetails details = productApi.getProductDetails(productId);
In the 'details' object, both ProdId & ProdName are coming as null.
Am I missing anything here? Firstly, Is it possible to get response as JSON instead of XML?
If that RESTful service is programmed to return only xml-response, then you cannot ask it to give you json-based response.
But in your case the problem is with class where you want to map the result.
This xml response actually wraps ProductDetails tag into ns3:Products.
So you need to create another class which will hold a reference to ProductDetails object:
public class Product { //class name can be anything
private ProductDetails ProductDetails;
//getters, setters
}
Then change the type of getProductDetails method to Product.
If you still get nulls in your response, then it's probably because of ObjectMapper configuration. But you can always add #JsonProperty annotation for your fields (in
this case it would be #JsonProperty("ProductDetails") for ProductDetails field in Product, and #JsonProperty("ProdId") and #JsonProperty("ProdName") for fields in ProductDetails).
I am trying to generate rest service using Apache CXF and Jackson data-binding. here I don't want to use #XmlRootElement annotation. when I try below code the request object coming like a null object.
here is my service interface
#POST
#Path("/getusers/")
#Consumes("application/json")
#Produces("application/json")
public List<UserDetails> getusers(UserDetails userDetails) throws ServiceException;
here is my domain object
public class UserDetails implements Serializable{
private String userName;
private int userId;
public UserDetails(){
}
//getters and setters...
}
The Json Object looks like
{
"id" : "102",
"username" : "scott"
}
And I am getting null-pointer exception for the request object
how do I access my request object
Note: here I am using Jackson Data-Binding
Your JSON contains username while the member is called userName. Also, id and userId are different.
You have three options:
Change the names of the UserDetails members to match the fields in the JSON object.
Change the names of the JSON object to match the member names of UserDetails.
Use #JsonProperty to configure the JSON object name to be bound to a UserDetails member.
Ignore a java bean field while converting to jSON
I am having a java bean and sending JSON as response , In that java bean I want to have
some transient fields , that should not come into JSON .
#XmlRootElement(name = "sample")
class Sample{
private String field1;
#XmlTransient
private String transientField;
//Getter and setters
public String toJSON() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
}
When I am calling toJSON method I am still getting "transientField" in JSON.
And I have a get rest API that returns this Sample JSON as response.
#GET
#Path("/somePath/")
#Produces({"application/json"})
Sample getSample();
In this response also I am getting that transient field .
Am I doing something wrong? Please help me to do this .
Try using #JsonIgnore instead.
method 1: use annotation #JsonIgnoreProperties("fieldname") to your POJO
example : #JsonIgnoreProperties(ignoreUnknown = true, value = {"fieldTobeIgnored"})
method 2:#JsonIgnore for a specific field that is to be ignored deserializing JSON
I have a java web maven project with JAX-RS using resteasy version 2.2.1.GA implementation. All JAX-RS resources on the project produces y consumes application/json. My problem is that when I returning a single POJO, even an array of this, only serialize the values of the attributes.
Example:
Given the following classes:
public class Pojo {
private Integer attr1;
private String attr2;
// GETTERs and SETTERs
}
#Path("pojos")
#Consumes("application/json")
#Produces("application/json")
public class PojoResource {
#GET
public Response list() {
List<Pojo> listResult = new ArrayList<>();
Pojo pojo = new Pojo();
pojo.setAttr1(1);
pojo.setAttr2("asdf");
listResult.add(pojo);
return Response.ok().entity(listResult).build();
}
}
If I do a GET request to /pojos, the result for the example above is [[1, "asdf"]], instead of [{"attr1":1,"attr2":"asdf"}]
I don't know if a need to write a specific Provider. My project configuration is similar to this.
I realized my mistake is that data recovery in layer model is as a vector of objects and return that without processing (create a POJO that represent the data).