eclipse-ee4j / eclipse-ee4j/jersey
Improved serialization of java.util.Map
- Dominant language
- Java
- Stars
- 730
- Forks
- 382
- PR merge metrics
- No merged PRs in 30d
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 yourMap = new LinkedHashMap();
...
}
Please see this mailing list discussion for more information:
[http://old.nabble.com/Custom-mapping-for-Maps-in-JAXB-ts28779221r0.html](http://old.nabble.com/Custom-mapping-for-Maps-in-JAXB-ts28779221r0.html)
NOTE: This approach seems to work nicely for Map. 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.
#### Environment
Operating System: All
Platform: All
URL: [http://old.nabble.com/Custom-mapping-for-Maps-in-JAXB-ts28779221r0.html](http://old.nabble.com/Custom-mapping-for-Maps-in-JAXB-ts28779221r0.html)
Contributor guide
Research direction
Start with the JsonMapAdapter example in the issue and review how jersey-json uses JAXB and @XmlJavaTypeAdapter for Map fields. Use the linked mailing-list discussion to understand the proposed mapping, then investigate support for Map and JAXB-annotated values. Done means natural JSON object keys are supported without a custom adapter, with the value limitations documented or addressed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100