Java – How to write a generic method that accepts any Java object and converts it to a JSON string

How to write a generic method that accepts any Java object and converts it to a JSON string… here is a solution to the problem.

How to write a generic method that accepts any Java object and converts it to a JSON string

I’m writing some ajax controllers for Spring MVC-based applications. Now in a class, I have three methods for three independent ajax call handlers with the same root url (that’s why I put them in one class). Now in each controller I have to return a JSON (stringified), and I’m using Object Mapper to implement it. But when I saw that the three methods looked exactly similar except for the parameter types, it occurred to me if there was a way to make the code more elegant.

The method called by the ajax controller

private String translateGetABCResponseToString(ABC response) {
        try {
            return mapper.writeValueAsString(response);
        } catch (JsonProcessingException ex) {
            throw new ValidationException(ex);
        }
    }

private String translateGetDEFResponseToString(DEF response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }

private String translateGetXYZResponseToString(XYZ response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }

Now, what I want is if there is a way to create one, because all three methods essentially do the same thing.

Solution

Just use the object:

private String translateObjectToString(Object obj) {
    try {
        return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new ValidationException(ex);
    }
}

Mapper doesn’t care what you give it. Everything will be fine.

Related Problems and Solutions