Jackson doesn't serialize hashmap - java

I have this method:
private String serializeToJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}
with this item:
and yet json equals:
{
"saveDate" : "12:29:29 29-Mar-02015"
}
why is failureDict not serialize?
and this is the item:
public class FailedResponses {
HashMap<String, Set<String>> failuresDict;
public String saveDate;
public FailedResponses() {
failuresDict = new HashMap<>();
}

Jackson will work magic on public fields or public getters and setters. I'd recommend that you make the fields of your object private for better encapsulation, and add the public getters/setters to allow jackson to de/serialize it.
Personally I like to use the jackson annotations to make it explicit what the object is being used for, and so that you have full control over the naming of the fields that jackson creates, without having to create non-idiomatic getter/setter or variable names

Related

Deserialize JSON object from MongoDB to Java object on GET request

I have some nested classes in Java, simplified here. Getters and setters exist.
Example
public class Planet {
#JsonProperty("name")
private String name;
#JsonProperty("moons")
private List<Moon> moons;
}
public class Moon {
#JsonProperty("moonname")
private String name;
#JsonProperty("craters")
private int craters;
}
I want to be able to deserialize the records on mongo (following this same structure) to java objects on the rest controller, specifically the HTTP GET request.
#RestController
#RequestMapping("/planets")
public class PlanetController {
#Autowired
private PlanetService planetService;
#RequestMapping("/")
public List<Planet> getAllPlanets() {
//Need to deserialize here
return planetService.getAll();
}
#RequestMapping("/{name}")
public Planet getItemsWithName(#PathVariable("name") String name) {
//deserialize here
return planetService.getEntryWithName(name.toLowerCase());
}
PlanetService.getAll() is expecting return type of List. getEntryWithName() is expecting return type of Planet.
How can I loop the results in the getAll() so I can deserialize them before they are returned?
Using Jackson's object mapper, I can do the serialization of a Java object to a JSON object.
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("target/mars.json"), mars);
} catch (IOException e) {
e.printStackTrace();
}
I can probably use readValue for the opposite process but I don't know how to loop the results.
I will appreciate the help. Let me know if something is not clear.
public List<Planet> getAllPlanets() {
List<Planet> planets = planetService.getAll();
String jsonString = new ObjectMapper().writeValueAsString(planets);
return planets;
}

How parse nested escaped json with Jackson?

Consider json:
{
"name": "myName",
"myNestedJson": "{\"key\":\"value\"}"
}
Should be parsed into classes:
public class MyDto {
String name;
Attributes myNestedJson;
}
public class Attributes {
String key;
}
Can it be parsed without writing stream parser? (Note that myNestedJson contains json escaped json string)
I think you can add a constructor to Attributes that takes a String
class Attributes {
String key;
public Attributes() {}
public Attributes(String s) {
// Here, s is {"key":"value"} you can parse it into an Attributes
// (this will use the no-arg constructor)
try {
ObjectMapper objectMapper = new ObjectMapper();
Attributes a = objectMapper.readValue(s, Attributes.class);
this.key = a.key;
} catch(Exception e) {/*handle that*/}
}
// GETTERS/SETTERS
}
Then you can parse it this way:
ObjectMapper objectMapper = new ObjectMapper();
MyDto myDto = objectMapper.readValue(json, MyDto.class);
This is a little dirty but your original JSON is too :)

serialize json array into java objects

I have a JSON array like as shown below which I need to serialize it to my class. I am using Jackson in my project.
[
{
"clientId": "111",
"clientName": "mask",
"clientKey": "abc1",
"clientValue": {}
},
{
"clientId": "111",
"clientName": "mask",
"clientKey": "abc2",
"clientValue": {}
}
]
In above JSON array, clientValue will have another JSON object in it. How can I serialize my above JSON array into my java class using Jackson?
public class DataRequest {
#JsonProperty("clientId")
private String clientId;
#JsonProperty("clientName")
private int clientName;
#JsonProperty("clientKey")
private String clientKey;
#JsonProperty("clientValue")
private Map<String, Object> clientValue;
//getters and setters
}
I have not used jackson before so I am not sure how can I use it to serialize my JSON array into Java objects? I am using jackson annotation here to serialize stuff but not sure what will be my next step?
You can create a utility function shown below. You may want to change the Deserialization feature based on your business needs. In my case, I did not want to fail on unknown properties => (FAIL_ON_UNKNOWN_PROPERTIES, false)
static <T> T mapJson(String body,
com.fasterxml.jackson.core.type.TypeReference<T> reference) {
T model = null;
if(body == null) {
return model;
}
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
try {
model = mapper.readValue(body, reference);
} catch (IOException e) {
//TODO: log error and handle accordingly
}
return model;
}
You can call it using similar approach as shown below:
mapJson(clientValueJsonString,
new com.fasterxml.jackson.core.type.TypeReference<List<DataRequest>>(){});
You can try #JsonAnyGetter and #JsonAnySetter annotations with an inner class object. Also clientName should have type String, not int.
public class DataRequest {
private String clientId;
private String clientName;
private String clientKey;
private ClientValue clientValue;
//getters and setters
}
public class ClientValue {
private Map<String, String> properties;
#JsonAnySetter
public void add(String key, String value) {
properties.put(key, value);
}
#JsonAnyGetter
public Map<String,String> getProperties() {
return properties;
}
}

JSON string to Java object with Jackson

This is probably one of those questions where the title says it all.
I am quite fascinated by the ObjectMapper's readValue(file, class) method, found within the Jackson library which reads a JSON string from a file and assigns it to an object.
I'm curious if this is possible to do by simply getting JSON from a string and applying it to an object.
Some sort of alternative readValue() method, which takes a String, instead of a file, and assigns it to an object?
For instance, while the default readValue(file, class) method looks like this:
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("C:\\student.json", Student.class);
I was wondering if there was some method in Jackson, which allowed the following:
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("{\"id\":100,\"firstName\":\"Adam\"}", Student.class);
The second example takes a string and an object of a class while the first one takes a file and an object of a class.
I just want to cut out the middle man, in this case, the file.
Is this doable or does no such method exist within the constraints of Jackson?
Try this,
You can't create a new string like your doing.
String string = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = mapper.readValue(string, Student.class);
And instead of handling errors in every mapper.readValue(json,Class) you can write a helper class which has another Generic method.
and use
String jsonString = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = JSONUtils.convertToObject(jsonString,Student.class);
I'm returning nulland fancying printing trace & checking null later on. You can handle error cases on your own way.
public class JSONUtils {
public static String convertToJSON(Object object)
{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json;
try {
json = ow.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
return convertToJSON(e);
}
return json;
}
public static <T> T convertToObject(Class<T> clazz,String jsonString)
{
try {
ObjectMapper mapper = new ObjectMapper();
return (T)mapper.readValue(jsonString, clazz);
}catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}

jackson delay deserializing field

I have a class like this:
public class DeserializedHeader
int typeToClassId;
Object obj
I know what type of object obj is based on the typeToClassId, which is unfortunately only known at runtime.
I want to parse obj out based on typeToClassId - what's the best approach here? Annotations seem like they're out, and something based on ObjectMapper seems right, but I'm having trouble figuring out what the best approach is likely to be.
Something along the lines of
Class clazz = lookUpClassBasedOnId(typeToClassId)
objectMapper.readValue(obj, clazz)
Obviously, this doesn't work since obj is already deserialized... but could I do this in 2 steps somehow, perhaps with convertValue?
This is really complex and painful problem. I do not know any sophisticated and elegant solution, but I can share with you my idea which I developed. I have created example program which help me to show you how you can solve your problem. At the beginning I have created two simple POJO classes:
class Product {
private String name;
// getters/setters/toString
}
and
class Entity {
private long id;
// getters/setters/toString
}
Example input JSON for those classes could look like this. For Product class:
{
"typeToClassId" : 33,
"obj" : {
"name" : "Computer"
}
}
and for Entity class:
{
"typeToClassId" : 45,
"obj" : {
"id" : 10
}
}
The main functionality which we want to use is "partial serializing/deserializing". To do this we will enable FAIL_ON_UNKNOWN_PROPERTIES feature on ObjectMapper. Now we have to create two classes which define typeToClassId and obj properties.
class HeaderType {
private int typeToClassId;
public int getTypeToClassId() {
return typeToClassId;
}
public void setTypeToClassId(int typeToClassId) {
this.typeToClassId = typeToClassId;
}
#Override
public String toString() {
return "HeaderType [typeToClassId=" + typeToClassId + "]";
}
}
class HeaderObject<T> {
private T obj;
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
#Override
public String toString() {
return "HeaderObject [obj=" + obj + "]";
}
}
And, finally source code which can parse JSON:
// Simple binding
Map<Integer, Class<?>> classResolverMap = new HashMap<Integer, Class<?>>();
classResolverMap.put(33, Product.class);
classResolverMap.put(45, Entity.class);
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
String json = "{...}";
// Parse type
HeaderType headerType = mapper.readValue(json, HeaderType.class);
// Retrieve class by integer value
Class<?> clazz = classResolverMap.get(headerType.getTypeToClassId());
// Create dynamic type
JavaType type = mapper.getTypeFactory().constructParametricType(HeaderObject.class, clazz);
// Parse object
HeaderObject<?> headerObject = (HeaderObject<?>) mapper.readValue(json, type);
// Get the object
Object result = headerObject.getObj();
System.out.println(result);
Helpful links:
How To Convert Java Map To / From JSON (Jackson).
java jackson parse object containing a generic type object.

Categories

Resources