1

Is there a way I can make the static method toObject generic by passing the T class and return type T?

public class JsonUtil { private JsonUtil() { } public static Object toObject(String jsonString, Class clazz, boolean unwrapRootValue) throws TechnicalException { ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter(); if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { throw new TechnicalException("Exception while converting JSON to Object", e); } } } 
2
  • 3
    JsonConverter would be a much better name for your class than JsonUtil. “Util” says nothing about what a class does. Commented Sep 23, 2019 at 4:23
  • I agree with the naming convention @VGR Commented Sep 23, 2019 at 4:24

2 Answers 2

3

Sure. Just specify a generic type parameter on the method itself, and use it for both the return type and the clazz parameter:

public static <T> T toObject(String jsonString, Class<T> clazz, boolean unwrapRootValue) throws TechnicalException { /* ... */ } 
Sign up to request clarification or add additional context in comments.

Comments

2
public class JsonUtil { private JsonUtil() { } public static <T> T toObject(String jsonString, Class<? extends T> clazz, boolean unwrapRootValue) throws TechnicalException { ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter(); if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { throw new TechnicalException("Exception while converting JSON to Object", e); } } } 

3 Comments

I see you removed Class<? super T>, however, Class<? extends T> might actually be useful. I haven't thought it through enough to determine if it would have any utility when casting toObject as a method reference.
No need to cast the result of mapper.readValue(). It's already generic.
@Robby Cornelissen Thanks alot! Answer has been fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.