MessageBodyWriter not found for media type=application/json

后端 未结 10 1619
庸人自扰
庸人自扰 2020-11-30 02:13

I am facing issues while consuming JAX-RS services as JSON.

Below I have added my code.

This is my service class:

//Sets the path to base URL         


        
10条回答
  •  Happy的楠姐
    2020-11-30 02:40

    In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:

    1. you have jersey-media-json-jackson in you pom.xml if using maven or added to your build path;
    2. you have an empty constructor in the data type you are trying to de-/serialize;
    3. you have the relevant annotation at the class and field level for your custom data type (xmlelement and/or jsonproperty);

    However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:

    GenericEntity entity = new GenericEntity(myObj) {};
    return Response.status(httpCode).entity(entity).build();
    

    This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:

    org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain
    

    So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.

提交回复
热议问题