Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

java - Unwrap a element in Jackson/Jaxb

I am using Jersey+Jackon to make a REST API which works with JSON.

Assume that I have a class as follows:

@XmlRootElement
public class A {
    public String s;
}

and here is my jersey method which uses the class:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Object get(@PathParam("id") String id) throws Exception{
    A[] a= new A[2];
    a[0] = new A();
    a[0].s="abc";
    a[1] = new A();
    a[1].s="def";
    return a;
}

the out put is:

{"a":[{"s":"abc"},{"s":"def"}]}

but I want it to be like this:

[{"s":"abc"},{"s":"def"}]

What should I do? Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your requirement seems to be to drop the root element from json string. This can be configured in Jersey as follows. In Jersey, whether dropping root element is configured by JSONConfiguration.rootUnwrapping(). More details can be found in JSON support in Jersey and CXF.

Here's a sample code that does this.

   @Provider
   public class MyJAXBContextResolver implements ContextResolver<JAXBContext> {

       private JAXBContext context;
       private Class[] types = {StatusInfoBean.class, JobInfoBean.class};

       public MyJAXBContextResolver() throws Exception {
           this.context = new JSONJAXBContext(
                   JSONConfiguration.mapped()
                                      .rootUnwrapping(true)
                                      .arrays("jobs")
                                      .nonStrings("pages", "tonerRemaining")
                                      .build(),
                   types);
       }

       public JAXBContext getContext(Class<?> objectType) {
           return (types[0].equals(objectType)) ? context : null;
       }
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...