jersey
  1. jersey
  2. JERSEY-551

Improved serialization of java.util.Map

    Details

    • Issuezilla Id:
      551

      Description

      Currently, to serialize java.util.Map objects to JSON, one needs to write a
      special @XmlJavaTypeAdapter annotation and usually covert the map into list of
      (key,value) entires, which are then marshalled/unmarshalled by JAXB.
      The representation for a key/value pair produced by this approach usually looks
      like this:

      {"key": "MyKey", "value" : "MyValue"}

      This is not very natural for JSON, as

      {"MyKey":"MyValue"}

      would be a more usual
      JSON-like representation. Unfortunately, this JSON-friendly representation
      cannot be easily produced by jersey-json, because it works via JAXB and JAXB
      cannot produce this out of the box easily, as it relies on XML Schemas and this
      representation requires XML tag names that are dynamic, which is impossible.

      Therefore, it would be nice to introduce the possibility to serialize Maps into
      a natural JSON format.

      Please find attached a class called JsonMapAdapter.
      It can be used like this to achieve the desired effect:

      @XmlRootElement(name="YourClassElementName")
      class YourClass {
      ...

      @XmlElement(name="YourMapElementName")
      // Here is the trick: Use use special map adapter for maps (see below)
      @XmlJavaTypeAdapter(JsonMapAdapter.class)
      private Map<String,String> yourMap = new LinkedHashMap<String,String>();

      ...
      }

      Please see this mailing list discussion for more information:
      http://old.nabble.com/Custom-mapping-for-Maps-in-JAXB-ts28779221r0.html

      NOTE: This approach seems to work nicely for Map<String,String>. But if values
      are JAXB-annotated classes, it most likely would not work out of the box. The
      way to solve this issue still needs to be investigated.

      1. JsonMapAdapter.java
        7 kB
        romixlev
      2. JsonMapAdapter.java
        2 kB
        romixlev

        Activity

          People

          • Assignee:
            Unassigned
            Reporter:
            romixlev
          • Votes:
            2 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

            • Created:
              Updated: