Specific MessageBodyWriter for the field

Say I have a data class in a JAX-RS 1 environment (RestEasy 2 with a Jackson provider), for example:

class Foo {
   int id;
   String name;
   Bar bar;

   ...
}

with Bar:

class Bar {
   int one;
   String two;
}

Now I want to Barserialize in a special way (perhaps depending on the type of medium that was requested (or depending on the phase of the moon), I would writeMessageBodyWriter<Bar>

@Provider
@Produces("application/json")
public class BarWriter implements MessageBodyWriter<Bar> {
   ...
}

which works very well if Barrequested independently, as in

@GET @Path("bar")  
public Bar getBar() return new Bar(...); }

But when I ask Foo, as in

@GET @Path("foo")  
public Foo getFoo() return new Foo(...); }

The message author is ignored.

Now I want this one to MessageBodyWriteralso be used when I return FooorList<Bar>

, MessageBodyWriter List, , Bar .

, ? Jackson Bar, , RestEasy ( , , ).

+5
3

, , . JAX-RS , , , . , , Bar, :

@GET @Path("bar")  
public Bar getBar() { return new Bar(...); }

JAX-RS Bar, . :

@GET @Path("foo")  
public Foo getFoo() { return new Foo(...); }

, ( ) , return content-type. , JSON XML, JAX-RS . Aka, , A , A, , A .

Jackson, Bar? :

public class BarSerializer extends JsonSerializer<Bar> {

    @Override
    public void serialize(final Bar value, final JsonGenerator jgen,
            final SerializerProvider provider) throws IOException,
            JsonProcessingException {

        jgen.writeStartObject();
        jgen.writeFieldName("myBar");
        jgen.writeString(value.getTwo());
        jgen.writeEndObject();
    }
}

:

@JsonSerialize(using=BarSerializer.class)
class Bar {
   int one;
   String two;
}

, , JSON , , JsonDeserializer.

, jackson-mapper jackson-jaxrs (, , jackson-core).

+6

JAX-RS MessageBodyWriter , (. 4.2.2 Message Body Writer) ), MessageBodyWriter , .

, MessageBodyWriter , , , . ( javax.ws.rs.ext.Providers getMessageBodyWriter()), , xml/json/etc , , . xml- .

+1

All Articles