I wrote a Generic method which works fine converting any Json object to Generic Object.
public <T> T convertJsontoObject (String jsonObj, Class<T> any Type) throws JsonMappingException, JsonProcessingException { ObjectMapper objectMap = new ObjectMapper(); return objectMap.readValue(jsonObj, any Type); }
But has an issue while converting the Generic Object type to JSON format with the below code format. Would someone help me or guide me with related code.. I am not sure how to retain an Object from Generic class type as the method doesn’t support for generic and I want to have a Generic method to perform the conversions….
public <T> String convertObjectToJson(Class<T> anyType) { String jsonStringObj = ""; try { jsonStringObj = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(anyType);} }
Advertisement
Answer
When you return a String you don’t need to use generics and you can receive only an Object on methods
// you can treate try and catch inside them as you prefer public static <T> T fromJson(String json, Class<T> classToReturn) throws Exception{ return new ObjectMapper().readValue(json, classToReturn); } public static String toJson(Object obj) throws Exception{ return new ObjectMapper().writeValueAsString(obj); } public static String toJsonPrettyNonNullTreatingDateTypes(Object obj) throws Exception{ return new ObjectMapper() .setSerializationInclusion(Include.NON_NULL) .setSerializationInclusion(Include.NON_EMPTY) .registerModule(new JavaTimeModule() ); .writerWithDefaultPrettyPrinter() .writeValueAsString(obj); }
using them
MyObject obj = fromJson(jsonString, MyObject.class ); String json = toJson(new MyObject()); // Object can accept any types String json = toJsonPrettyNonNullTreatingDateTypes(new MyObject());