0

I'm currently trying to output a map in JSON from Jersey. I'm aiming for a normal object in this way:

map: { key1 : value1, key2: value2 }

However Jersey opts for a more confusing way:

"storage":
  {"entry":[
    {"key":"IRON","value":792},
    {"key":"COPPER","value":2489},
    {"key":"CARDBOARD","value":14536}
    ]
  }
}

I managed to map some values with a custom map using JAXBElement:

@XmlRootElement
public class MapDTO<K, V> {

    @XmlAnyElement
    private List<JAXBElement<V>> elements = new ArrayList<>();

    public MapDTO(){}

    public MapDTO(Map<K,V> map) {
        map.forEach((k, v) ->
                elements.add(
                        new JAXBElement(new QName(k.toString()), v.getClass(), v))
        );
    }
}

However for some reason the output of this results in a map of key: Array where each key shows an array of a single element:

"storage":{
  "CIRCUITS":[3379992],
  "CARDBOARD":[84838963545],
  "COPPER_CABLE":[1673987]
}

Anyone know why this is or is there a way of doing it better?

I know this has been asked before, however the accepted question seems like a non-solution since it can't compile, and the other solutions does not seem to work. Since this question is over a year old, maybe someone can bring some new light to this question.

  • Not even [this](https://stackoverflow.com/questions/5794713/java-util-map-to-json-object-with-jersey-jaxb-jackson/37440199#37440199) one? – Rômulo M. Farias Nov 14 '17 at 19:16
  • That solution throws Exception 'Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.inject.Binder', Will look more into it since last time it was some time ago. – Juan F. Caracciolo Nov 14 '17 at 20:31
  • Was a version problem, i manage to get it working, still same output. How do i know if jersey is really using jackson? – Juan F. Caracciolo Nov 14 '17 at 20:37
  • To check if you're using Jackson, set some breakpoints in JacksonJaxbJsonProvider and JacksonJsonProvider (both from the jersey-media-json dependency) – ChrisO Nov 30 '17 at 22:48

0 Answers0