0

We want to write an API that looks something like this:

@XmlRootElement(name = "MyData")
@XmlAccessorType(XmlAccessType.FIELD)
public static class MyData {
    public String name;
    public Map<String,String> data;
}

@GET
@Path("/mydata")
public MyData getMyData() {
    MyData ret = new MyData();
    ret.name = "map data";
    ret.data = new HashMap<>();
    ret.data.put("a1", "b1");
    ret.data.put("a2", "b2");
    return ret;
}

But here's the sticking point we cannot seem to get around: we want this to return a JSON structure something like this:

{
   "MyData":{
      "name":"map data",
      "data":{
         "a1": "b1",
         "a2": "b2"
      }
   }
}

and we can't figure out how to get beyond something like

{
   "MyData":{
      "name":"map data",
      "data":{
         "entry":[
            {
               "key":"a1",
               "value":"b1"
            },
            {
               "key":"a2",
               "value":"b2"
            }
         ]
      }
   }
}

Any idea how we might do this? I'm pretty sure this can be done, because I once saw a demo of it. We're using tomcat, Java 7, CXF 2.7.3, and Jackson 2.1.2. Two points:

  • Note that it doesn't have to contain a Map necessarily: all we need is to marsall a bunch of key/values where the keys are not known in advance.
  • We have to go both directions - we need to implement PUT/POST as well as GET with this syntax in the representation.
fool4jesus
  • 2,147
  • 3
  • 23
  • 34
  • What JSON library do you use for the mapping? How is it configured? –  Apr 14 '14 at 13:02
  • I noted that we are using Jackson 2.1.2 under CXF 2.7.3. It's a very vanilla configuration. I suspect there is an XML mapper or something that can be applied, but that's what I do not know. – fool4jesus Apr 14 '14 at 16:18
  • Maybe [that helps](http://stackoverflow.com/a/20396007). – lefloh Apr 14 '14 at 18:35
  • Lefloh, I will check that out. I don't think it answers the question directly, but I think it *might* point me to a possible solution. Thank you! – fool4jesus Apr 14 '14 at 19:05
  • 1
    Why was I downvoted on this? It doesn't seem like a worthless question. My research effort consisted of spending many hours reading CXF documentation and googling Stack Overflow answers. – fool4jesus May 07 '14 at 17:11

1 Answers1

0

If you want to return only JSON (do not support XML), then simply remove all JAXB annotations from MyData and you will get a pretty good structure, but without the wrapping "MyData" element (which seems redundant to me). You could e.g use core Jackson annotations, like @JsonIgnore (instead of JAXB's). If you want to add the root wrapping element, you could set the WRAP_ROOT_VALUE to true.

V G
  • 18,822
  • 6
  • 51
  • 89