How to exactly match json output from cxf?
Edit: i was confused-- were using cxf, not jersey. Is there a way to convert an annotated object to json that is similar to jackson's ObjectMapper?
original msg:
Hi, We are currently using jaxrs to convert our web responses to xml/json. What I would like to do now, however, is generate an equivalent json string inside my code using ObjectMapper(?).
For instance, given a controller and jaxb-annotated return object:
@Path("/foo")
@Produces({"application/json", "application/xml"})
public class FooController {
@GET
@Path("/some_action")
public TopDTO someAction(@QueryParam("arg") String arg) {
...
}
}
@XmlRootElement(name="topDTO")
@XmlAccessorType(XmlAccessType.NONE)
public class TopDTO {
...
@XmlAttribute(name="attr")
public String getAttr() {
return "blah";
}
@XmlElement(name="innerDTO")
public InnerDTO getInnerDTO() {
...
}
}
@XmlRootElement(name="innerDTO")
@XmlAccessorType(XmlAccessType.NONE)
public class InnerDTO {
...
}
Hitting http://myserver/.../foo.json puts out some pretty json:
{"topDTO":{"@attr":"blah","innerDTO":...}}
Now I would like to be able to generate that exact json internally:
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setSerializationInclusion(Incl开发者_如何学Gousion.ALWAYS);
mapper.getSerializationConfig().set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
mapper.getSerializationConfig().set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
return mapper.writeValueAsString(snapshotDTO);
However, this doesn't seem to work at all; most of the annotated attributes and elements are missing, the attributes aren't prefixed with "@" as they are with jaxrs output, etc.
Am i missing something simple? How does jaxrs itself convert an annotated object to a json string?
Thanks! joe
Use the JSONJAXBContext to create a marshaller and use it to serialize your object to the JSON format. I don't think you need jackson.
JSONJAXBContext c = create the context
JSONMarshaller m = c.createJSONMarshaller();
YourJAXBObject obj = your object
StringWriter writer = some writer
m.marshallToJSON(obj, writer);
It actually looks like not only are you using CXF, you are not using Jackson's json serialization. Why? Because Jackson does not add '@' in front of things declared as attributes.
If you want to use ObjectMapper you probably want to start with defaults, and try to change things according to what you want to change, and not by starting with a set of configuration overrides (for example: you are disabling getter/setter auto-detection, which doesn't seem like something you should be doing).
Yes. Can set Jackson as a provider as in http://cxf.apache.org/docs/jax-rs-data-bindings.html . I have observed Jackson is simple and convenient in many ways.
精彩评论