How to exactly match json output with cxf?

Edit: I was confused - used cxf, not knitwear. Is there a way to convert an annotated object to json, which is similar to jackson ObjectMapper?

original posts:

Hi, We are currently using jaxrs to convert our answers on the web to xml / json. However, now I would like to create an equivalent json string inside my code using ObjectMapper (?).

For example, given the controller and the 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 {
    ...  
}

Pressing http: //myserver/.../foo.json produces some nice json:

{"topDTO":{"@attr":"blah","innerDTO":...}}

Now, I would like to be able to generate this exact json inside:

ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.ALWAYS);            
mapper.getSerializationConfig().set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
mapper.getSerializationConfig().set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
return mapper.writeValueAsString(snapshotDTO);

, , ; , "@", jaxrs ..

- ? jaxrs json?

!

+3
3

JSONJAXBContext JSON. , .

  JSONJAXBContext c = create the context
  JSONMarshaller m = c.createJSONMarshaller();
  YourJAXBObject obj = your object
  StringWriter writer = some writer
  m.marshallToJSON(obj, writer);
+3

CXF, Jackson json. ? '@' , .

ObjectMapper, , , , , , (: / , , ).

+2

Yes. You can install Jackson as a provider, as in http://cxf.apache.org/docs/jax-rs-data-bindings.html . I noticed that Jackson is simple and convenient in many ways.

0
source

Source: https://habr.com/ru/post/1789958/


All Articles