Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jersey 2.0 JSON Pojo Mapper sample
import org.glassfish.jersey.media.json.JsonJacksonModule;
import org.glassfish.jersey.server.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.glassfish.jersey.test.spi.TestContainer;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import static junit.framework.Assert.assertNotNull;
public class ServiceTest extends JerseyTest {
protected static final String MIME_TYPE = MediaType.APPLICATION_JSON;
@Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
ResourceConfig resourceConfig = ResourceConfig.builder().addModules(new JsonJacksonModule()).addClasses(MyResource.class).build();
return Application.builder(resourceConfig).build();
}
@Override
protected javax.ws.rs.client.Client getClient(TestContainer tc, Application application) {
javax.ws.rs.client.Client origClient = super.getClient(tc, application);
for (Class<?> provider : JsonJacksonModule.getProviders()) {
origClient.configuration().register(provider);
}
origClient.configuration().register(JsonPojoMapperProvider.class);
return origClient;
}
@Test
public void pojoTest() {
Cluster c = target().path("foo").path("cluster").request(MIME_TYPE).get(Cluster.class);
assertNotNull(c);
}
}
#############################################################################################################################################
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
@Provider
public class JsonPojoMapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper pojoMapper;
public JsonPojoMapperProvider() {
pojoMapper = new ObjectMapper();
pojoMapper.configure(Feature.INDENT_OUTPUT, true);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return pojoMapper;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.