I have the following controller:
#RequestMapping(value = "/test/inst/", method = RequestMethod.POST)
public #ResponseBody ResponseDTO<InstDTO>
testPostREST(#RequestBody RequestDTO<InstDTO> instDTO) {
RequestDTO<InstDTO> dto = new RequestDTO<InstDTO>();
ResponseDTO<InstDTO> responseDto = new ResponseDTO<InstDTO>();
responseDto.setPayload(instDTO.getPayload());
return responseDto;
}
with the following request object:
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class RequestDTO<T> {
private List<T> payload;
public RequestDTO() {
System.out.println("constructor");
}
public RequestDTO(List<T> payload) {
this.payload = payload;
}
public List<T> getPayload() {
return payload;
}
public void setPayload(List<T> payload) {
this.payload = payload;
}
}
When the POST comes through and I look the object I get, the payload list has LinkedHashMap objects instead of objects of my DTO type.
How can I make spring+jackson convert the JSON into my DTO object. Bear in mind that I plan to reuse the wrapper ResponseDTO for other lists of objects and that's why I'm using a generic list (List).
Here's the JSON I'm trying.
{
"payload": [
{
"d": "Test 0",
"id": "abcde",
"c": "Test 0"
},
{
"d": "Test 1",
"id": "123",
"c": "Test 1"
}
]
}
Your code does not work due to type erasure. Jackson runtime does not know that you are trying to marshal the payload into InstitutionDTO objects (since this information has been erased at compile time). When Jackson looks at the payload, it sees valid JSON objects on the wire and a List<Object> on the Java side. It has no choice but to map the payload to a Map implementation, which in your case seems to be LinkedHashMap.
You may be able to achieve what you are looking for as follows:
class RequestDTO<T> {}
class ResponseDTO<T> {}
class InstitutionDTO {}
class InstitutionRequestDTO extends RequestDTO<InstitutionDTO>
class InstitutionResponseDTO extends ResponseDTO<InstitutionDTO>
#RequestMapping(value = "/test/institution/", method = RequestMethod.POST)
public #ResponseBody InstitutionResponseDTO
testPostREST(#RequestBody InstitutionRequestDTO institutionDTO) { }
Disclaimer: I haven't tried this code myself but most of my applications have code similar to this and it works with Jackson, Castor, Atom, etc. without a glitch.
If using Jackson isn't a requirement then you might want to consider using Gson instead.
You can tell Gson how to deserialize your json by just passing it a json string and the class that you want to deserialize. It would be pretty simple. I've included an example where I had to deserialize a response from a rest api below.
entity = response.getEntity();
jsonResponse = EntityUtils.toString(entity);
JsonNode root = mapper.readTree(jsonResponse).get("result");
returnedProduct = gson.fromJson(root.toString(),Product.class);
Related
Consider json input:
{
companies: [
{
"id": 1,
"name": "name1"
},
{
"id": 1,
"name": "name1"
}
],
nextPage: 2
}
How deserialize this into class:
public class MyClass {
List<String> companies;
Integer nextPage;
}
Where List<String> companies; consists of strings:
{"id": 1,"name": "name1"}
{"id": 1,"name": "name1"}
#JsonRawValue doesn't work for List<String> companies;
Is there a way to configure Jackson serialization to keep companies array with raw json string with annotations only? (E.g. without writing custom deserializator)
There is no annotation-only solution for your problem. Somehow you have to convert JSON Object to java.lang.String and you need to specify that conversion.
You can:
Write custom deserializer which is probably most obvious solution but forbidden in question.
Register custom com.fasterxml.jackson.databind.deser.DeserializationProblemHandler and handle com.fasterxml.jackson.databind.exc.MismatchedInputException situation in more sophisticated way.
Implement com.fasterxml.jackson.databind.util.Converter interface and convert JsonNode to String. It is semi-annotational way to solve a problem but we do not implement the worst part - deserialisation.
Let's go to point 2. right away.
2. DeserializationProblemHandler
Solution is pretty simple:
ObjectMapper mapper = new ObjectMapper();
mapper.addHandler(new DeserializationProblemHandler() {
#Override
public Object handleUnexpectedToken(DeserializationContext ctxt, JavaType targetType, JsonToken t, JsonParser p, String failureMsg) throws IOException {
if (targetType.getRawClass() == String.class) {
// read as tree and convert to String
return p.readValueAsTree().toString();
}
return super.handleUnexpectedToken(ctxt, targetType, t, p, failureMsg);
}
});
Read a whole piece of JSON as TreeNode and convert it to String using toString method. Helpfully, toString generates valid JSON. Downside, this solution has a global scope for given ObjectMapper instance.
3. Custom Converter
This solution requires to implement com.fasterxml.jackson.databind.util.Converter interface which converts com.fasterxml.jackson.databind.JsonNode to String:
class JsonNode2StringConverter implements Converter<JsonNode, String> {
#Override
public String convert(JsonNode value) {
return value.toString();
}
#Override
public JavaType getInputType(TypeFactory typeFactory) {
return typeFactory.constructType(new TypeReference<JsonNode>() {
});
}
#Override
public JavaType getOutputType(TypeFactory typeFactory) {
return typeFactory.constructType(new TypeReference<String>() {
});
}
}
and now, you can use annotation like below:
#JsonDeserialize(contentConverter = JsonNode2StringConverter.class)
private List<String> companies;
Solutions 2. and 3. solve this problem almost in the same way - read node and convert it back to JSON, but uses different approaches.
If, you want to avoid deserialising and serialising process you can take a look on solution provided in this article: Deserializing JSON property as String with Jackson and take a look at:
How to serialize JSON with array field to object with String field?
How to get a part of JSON as a plain text using Jackson
How to extract part of the original text from JSON with Jackson?
I am developing a restful web application using java and jax-rs. In server side, I have to accept Json type requests as given by the client using POST method.
#POST
#Path("/Request")
#Consumes(MediaType.APPLICATION_JSON)
public String process(SMessage message) throws Exception {
message.getHeader();
message.getBody();
}
The json object have two composite fields like in the below format.
{
"header": {
"serviceType": "A"
},
"body": {
"id": "1",
"name": "abc"
}
}
Based on the serviceType specified in the Header field, the parameters in the body will differ. I need to map this body field in to a java POJO class. The POJO class is not the same for all requests. How can I achieve this effectively?
If you are using Jackson as your JSON parser, a simple way is to declare body to be a JsonNode to handle dynamic keys as follows:
class MyResponse {
private MyHeader header;
private JsonNode body;
//general getters and setters
}
And I assumed that you have already a POJO for header such as:
class MyHeader {
private String serviceType;
//general getters and setters
}
Finally, let's verify that it works:
String responseStr = "{\"header\": {\"serviceType\": \"A\"},\"body\": {\"id\": \"1\",\"name\": \"abc\"}}";
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(responseStr, MyResponse.class);
System.out.println(myResponse.getBody().get("name").asText());
Console output:
abc
Another way to solve this issue is by using Map and everything else is the same:
class MyResponse {
private MyHeader header;
private Map<String, Object> body;
//general getters and setters
}
I am getting the below JSON response format from a third party web service:
{
"meta": {
"code": 200,
"requestId": "1"
},
"response": {
"locations": [
{
"id": "1",
"name": "XXX",
"contact": {
phone: '123',
email: 'abc'
},
"location": {
"address": [
"Finland"
]
}
},
{
// another location
}
]
}
}
And here is what I should return as a response from my own web service:
[
{
"id": "1",
"name": "XXX",
"phone": '123',
"address": "Finland"
},
{
// another location
}
]
What should I do? I've read some good stuff about Jackson but there are only a few simple examples where you map some simple JSON obj as is to POJO. In my case, I need to remove a few nodes, and also traverse deeper down the hierarchy to get the nested value. This is my baby step so far in my spring boot app:
#GET
#Path("{query}")
#Produces("application/json")
public String getVenues(#PathParam("query") String query){
return client.target(url).queryParam("query",query).request(...).get(String.class)
}
Any helps, pointers, recommendations are welcomed!
You are using JAX-RS annotations instead of the Spring web service annotations. You can make this work, but I would recommend going with the default Spring annotations because those are all autoconfigured for you if you're using the spring boot starter dependencies.
First thing - you need to create classes that are set up like the request and response. Something like this:
public class ThirdPartyResponse {
MetaData meta;
Response response;
}
public class Response {
List<Location> locations;
}
public class MetaData {
String code;
String requestId;
}
public class Location {
String id;
String name;
Contact contact;
LocationDetails location;
}
public class Contact {
String phone;
String email;
}
public class LocationDetails {
List<String> address;
}
You can use Jackson annotations to customize the deserialization, but by default it maps pretty logically to fields by name and the types you might expect (a JSON list named "locations" gets mapped to a List in your object named "locations", etc).
Next you'll want to use a #RestController annotated class for your service, which makes the service call to the third party service using RestTemplate, something like:
#RestController
public class Controller {
#Value("${url}")
String url;
#RequestMapping("/path"
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<Location> locations(#RequestParam String query) {
// RestTemplate will make the service call and handle the
// mapping from JSON to Java object
RestTemplate restTemplate = new RestTemplate();
ThirdPartyResponse response = restTemplate.getForObject(url, ThirdPartyResponse.class);
List<Location> myResponse = new List<>();
// ... do whatever processing you need here ...
// this response will be serialized as JSON "automatically"
return myResponse;
}
}
As you can see, Spring Boot abstracts away a lot of the JSON processing and makes it pretty painless.
Take a look at Spring's guides which are pretty helpful:
Consuming a service with RestTemplate
http://spring.io/guides/gs/consuming-rest/
Creating a web service using #RestController
https://spring.io/guides/gs/rest-service/
This can be done using google api JacksonFactory.
Below is my suggested solution for this.
First you should create a pojo class corrosponding to the json data you are recieving and the json data to which you are trying to convert.
Use google api client to map the keys to the pojo.
Below is the pojo classes corrosponding to the json data you are recieving.
import com.google.api.client.util.Key;
Class Response{
#Key("locations")
List<FromLocations> fromLocations;
}
import com.google.api.client.util.Key;
Class FromLocations
{
#Key("id")
String id;
#Key("name")
String name;
#Key("contact")
Contact contact;
#Key("location")
Location location;
}
Here Contact and Loaction will be a another classes using the same strategy;
Below is the pojo corrosponding to the json to which you want to convert.
Class ToLocations{
String id;
String name;
String phone;
String address;
}
Now you can parse the requset containing the json objec to the fromLocations class as below.
String responseMeta = response.parseAsString();
JSONObject queryJsonObject = new JSONObject(responseMeta);
if(queryJsonObject.has("locations")){
Response response = JacksonFactory.getDefaultInstance().fromString(responseMeta,Response.class);
List<FromLocations> fromLocationsList = response.getFromLocations();
}
Next step is to iterate the list fromLocationsList and get the desired values from each FromLocations object and add it to the ToLocations object.
Next the ToLocations object can be add it to a list and convert it to json.
Here's where I'm at. I've an MVC controller method that accepts JSON content. Because I need to validate it using JSON Schema, my controller maps the request body as a Jackson JsonNode.
Upon successful validation, I need to persist the data in Spring Couchbase repository. Consider the following snippet:
public class Foo
{
#Id
private String _id;
#Version
private Long _rev;
#Field
private JsonNode nodeData;
// .. Other data and members.
}
//
// Repository
//
#Repository
public interface FooRepository extends CrudRepository<Foo, String> {
}
When I store these elements into the Couch repository, what I'd like to see is something like this:
{
"_class": "Foo",
"field1": "field 1 data",
"nodeData" : {
"Some" : "additional data",
"from" : "JsonNode"
}
}
instead, what I see in the repository is something like this:
{
"_class": "Foo",
"field1": "field 1 data",
"nodeData" : {
"_children": {
"Some": {
"_value": "additional data",
"_class": "com.fasterxml.jackson.databind.node.TextNode"
},
"From": {
"_value": "jsonNode",
"_class": "com.fasterxml.jackson.databind.node.TextNode"
},
"_nodeFactory": {
"_cfgBigDecimalExact": false
}
}
}
Each stored property of the JsonNode is decorated with class information, and other meta-data, which is not desirable.
My question - is there a preferred way to get the CrudRepository to behave in the manner that I wish?
It doesn't work that way because serialization and de-serialization conventions are already established. You can override these conventions with custom serialization & de-serialization in Jackson-- but that might go beyond the "crude" approach you are looking for.
I see you want a one shoe fits all approach to data modeling.
Might i recommend storing a Map
#Field
private Map<String, String> data;
This map is private so its perfect.
You can then have two methods
one method puts to the map like so
ObjectMapper mapper = new ObjectMapper()
public void setFeild(String name, Object value) {
ObjectNode node new ObjectNode(JsonNodeFactory.instance);
node.put("clazz", value.getClass().getName());
if (value instance of String) {
node.put("value", value)
} else {
node.put("value", mapper.writeValueAsString(data));
}
data.put(name, node.toString());
}
the other gets from the map like so
public Object getField(String name) {
if (data.contains(name)) {
JsonNode node = mapper.readValue(data.get(name), JsonNode.class);
Class clazz = Class.forName(node.get("class").textValue());
if (clazz.equals(String.class) {
return node.get("value").textValue();
} else {
return (Object) mapper.readValue(node.get("value"), clazz);
}
}
}
You should update this implementation to handle Date, Integer, Boolean, Double ... etc the same way i am handling String-- POJOs are what you serialize/de-serialize to/from json.
I hope this makes sense.
I have
#RequestMapping(method = RequestMethod.GET)
#ResponseBody
SessionInfo register(UserProfile profileJson){
...
}
I pass profileJson this way:
http://server/url?profileJson={"email": "mymail#gmail.com"}
but my profileJson object has all null fields. What should I do to make spring parse my json?
The solution to this is so easy and simple it will practically make you laugh, but before I even get to it, let me first emphasize that no self-respecting Java developer would ever, and I mean EVER work with JSON without utilizing the Jackson high-performance JSON library.
Jackson is not only a work horse and a defacto JSON library for Java developers, but it also provides a whole suite of API calls that makes JSON integration with Java a piece of cake (you can download Jackson at http://jackson.codehaus.org/).
Now for the answer. Assuming that you have a UserProfile pojo that looks something like this:
public class UserProfile {
private String email;
// etc...
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// more getters and setters...
}
...then your Spring MVC method to convert a GET parameter name "profileJson" with JSON value of {"email": "mymail#gmail.com"} would look like this in your controller:
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper; // this is your lifesaver right here
//.. your controller class, blah blah blah
#RequestMapping(value="/register", method = RequestMethod.GET)
public SessionInfo register(#RequestParam("profileJson") String profileJson)
throws JsonMappingException, JsonParseException, IOException {
// now simply convert your JSON string into your UserProfile POJO
// using Jackson's ObjectMapper.readValue() method, whose first
// parameter your JSON parameter as String, and the second
// parameter is the POJO class.
UserProfile profile =
new ObjectMapper().readValue(profileJson, UserProfile.class);
System.out.println(profile.getEmail());
// rest of your code goes here.
}
Bam! You're done. I would encourage you to look through the bulk of Jackson API because, as I said, it is a lifesaver. For example, are you returning JSON from your controller at all? If so, all you need to do is include JSON in your lib, and return your POJO and Jackson will AUTOMATICALLY convert it into JSON. You can't get much easier than that. Cheers! :-)
This could be done with a custom editor, that converts the JSON into a UserProfile object:
public class UserProfileEditor extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
ObjectMapper mapper = new ObjectMapper();
UserProfile value = null;
try {
value = new UserProfile();
JsonNode root = mapper.readTree(text);
value.setEmail(root.path("email").asText());
} catch (IOException e) {
// handle error
}
setValue(value);
}
}
This is for registering the editor in the controller class:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserProfile.class, new UserProfileEditor());
}
And this is how to use the editor, to unmarshall the JSONP parameter:
#RequestMapping(value = "/jsonp", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
#ResponseBody
SessionInfo register(#RequestParam("profileJson") UserProfile profileJson){
...
}
You can create your own Converter and let Spring use it automatically where appropriate:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
#Component
class JsonToUserProfileConverter implements Converter<String, UserProfile> {
private final ObjectMapper jsonMapper = new ObjectMapper();
public UserProfile convert(String source) {
return jsonMapper.readValue(source, UserProfile.class);
}
}
As you can see in the following controller method nothing special is needed:
#GetMapping
#ResponseBody
public SessionInfo register(#RequestParam UserProfile userProfile) {
...
}
Spring picks up the converter automatically if you're using component scanning and annotate the converter class with #Component.
Learn more about Spring Converter and type conversions in Spring MVC.
This does solve my immediate issue, but I'm still curious as to how you might pass in multiple JSON objects via an AJAX call.
The best way to do this is to have a wrapper object that contains the two (or multiple) objects you want to pass. You then construct your JSON object as an array of the two objects i.e.
[
{
"name" : "object1",
"prop1" : "foo",
"prop2" : "bar"
},
{
"name" : "object2",
"prop1" : "hello",
"prop2" : "world"
}
]
Then in your controller method you recieve the request body as a single object and extract the two contained objects. i.e:
#RequestMapping(value="/handlePost", method = RequestMethod.POST, consumes = { "application/json" })
public void doPost(#RequestBody WrapperObject wrapperObj) {
Object obj1 = wrapperObj.getObj1;
Object obj2 = wrapperObj.getObj2;
//Do what you want with the objects...
}
The wrapper object would look something like...
public class WrapperObject {
private Object obj1;
private Object obj2;
public Object getObj1() {
return obj1;
}
public void setObj1(Object obj1) {
this.obj1 = obj1;
}
public Object getObj2() {
return obj2;
}
public void setObj2(Object obj2) {
this.obj2 = obj2;
}
}
Just add #RequestBody annotation before this param