Is there a method built in spring MockMVC to get json content as Object?

This might be of use:

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.togondo.config.database.MappingConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Getter
public class CustomResponseHandler<T> implements ResultHandler {

private final Class<? extends Collection> collectionClass;
private T responseObject;
private String responseData;
private final Class<T> type;
private Map<String, String> headers;
private String contentType;

public CustomResponseHandler() {
    this.type = null;
    this.collectionClass = null;
}

public CustomResponseHandler(Class type) {
    this.type = type;
    this.collectionClass = null;
}

public CustomResponseHandler(Class type, Class<? extends Collection> collectionClass) {
    this.type = type;
    this.collectionClass = collectionClass;
}


protected <T> T responseToObject(MockHttpServletResponse response, Class<T> type) throws IOException {
    String json = getResponseAsContentsAsString(response);
    if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
        return null;
    }
    return MappingConfig.getObjectMapper().readValue(json, type);
}

protected <T> T responseToObjectCollection(MockHttpServletResponse response, Class<? extends Collection> collectionType, Class<T> collectionContents) throws IOException {
    String json = getResponseAsContentsAsString(response);
    if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
        return null;
    }
    ObjectMapper mapper = MappingConfig.getObjectMapper();
    JavaType type = mapper.getTypeFactory().constructCollectionType(collectionType, collectionContents);
    return mapper.readValue(json, type);
}


protected String getResponseAsContentsAsString(MockHttpServletResponse response) throws IOException {
    String content = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getContentAsByteArray())));
    String line;
    while ((line = br.readLine()) != null)
        content += line;
    br.close();

    return content;
}

@Override
public void handle(MvcResult result) throws Exception {
    if( type != null ) {
        if (collectionClass != null) {
            responseObject = responseToObjectCollection(result.getResponse(), collectionClass, type);
        } else {
            responseObject = responseToObject(result.getResponse(), type);
        }
    }
    else {
        responseData = getResponseAsContentsAsString(result.getResponse());
    }

    headers = getHeaders(result);
    contentType = result.getResponse().getContentType();

    if (result.getResolvedException() != null) {
        log.error("Exception: {}", result.getResponse().getErrorMessage());
        log.error("Error: {}", result.getResolvedException());
    }
}

private Map<String, String> getHeaders(MvcResult result) {
    Map<String, String> headers = new HashMap<>();
    result.getResponse().getHeaderNames().forEach(
            header -> headers.put(header, result.getResponse().getHeader(header))
    );
    return headers;
}

public String getHeader(String headerName) {
    return headers.get(headerName);
}

public String getContentType() {
    return contentType;
}

}

And then use it in your tests like this:

CustomResponseHandler<MyObject> responseHandler = new CustomResponseHandler(MyObject.class);

mockMvc.perform(MockMvcRequestBuilders.get("/api/yourmom"))
            .andDo(responseHandler)
            .andExpect(status().isOk());


MyObject myObject = responseHandler.getResponseObject();

Or if you want to fetch collections:

CustomResponseHandler<Set<MyObject>> responseHandler = new CustomResponseHandler(MyObject.class, Set.class);
.
.
.
Set<MyObject> myObjectSet = responseHandler.getResponseObject();

As far as I know MockHttpServletResponse (Unlike RestTemplate) doesn't have any method which could convert returned JSON to a particular type.

So what you could do is use Jackson ObjectMapper to convert JSON string to a particular type

Something like this

String json = rt.getResponse().getContentAsString();
SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);

This will give you more control for you to assert different things.

Having said that, MockMvc::perform returns ResultActions which has a method andExpect which takes ResultMatcher. This has a lot of options to test the resulting json without converting it to an object.

For example

mvc.perform(  .....
                ......
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstname").value("john"))
                .andExpect(jsonPath("$.lastname").value("doe"))
                .andReturn();