Jersey: MessageBodyWriter not found for media type=application/json, type=class org.codehaus.jackson.node.ObjectNode?

前端 未结 4 1136
无人及你
无人及你 2020-12-17 15:57

I am using Jersey 2.8 Client to post data to RESTful endpoint. The code looks like

    final Client client = ClientBuilder.newClient();
    fina         


        
4条回答
  •  甜味超标
    2020-12-17 16:27

    If you ok using Jackson 1.x, then you need to the following 3 things.

    1. Add Jersey Jackson to your pom.xml:

    
        org.glassfish.jersey.media
        jersey-media-json-jackson
        2.8
    
    

    2. Create a ContextResolver:

    @Provider
    public class ObjectMapperProvider implements ContextResolver {
    
        final ObjectMapper defaultObjectMapper;
    
        public ObjectMapperProvider() {
            defaultObjectMapper = getObjectMapper();
        }
    
        @Override
        public ObjectMapper getContext(Class type) {
            return defaultObjectMapper;
        }
    
        public static ObjectMapper getObjectMapper() {
            return new ObjectMapper()
                    .configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false /* force ISO8601 */)
                    .configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true)
                    .configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, true)
                    .setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
        }
    }
    

    3. Register providers with ClientBuilder:

    final Client client = ClientBuilder.newBuilder()
            .register(ObjectMapperProvider.class)
            .register(JacksonFeature.class)
            .build();
    
    final WebTarget target = client.target(url).path("inventorySummary");
    
    final ObjectNode payload = ObjectMapperProvider.getObjectMapper().createObjectNode();
    payload.put("startDate", DateTime.now().toString());
    payload.put("endDate", DateTime.now().plusDays(30).toString());
    payload.put("networkId", 0);
    
    final Response response = target.request(MediaType.APPLICATION_JSON)
                                    .post(Entity.json(payload));
    
    assertStatus(Response.Status.OK.getStatusCode(), response);
    

提交回复
热议问题