Home > Java > javaTutorial > body text

How to Marshal a Map into `value` Format in JAXB?

DDD
Release: 2024-11-21 08:59:09
Original
200 people have browsed it

How to Marshal a Map into `value` Format in JAXB?

JAXB: Marshalling a Map into value Format

Context

JAXB natively supports marshalling a Map into a structure like this:

<map>
  <entry>
    <key> KEY </key>
    <value> VALUE </value>
  </entry>
  <entry>
    <key> KEY2 </key>
    <value> VALUE2 </value>
  </entry>
  ...
</map>
Copy after login

However, in certain cases, it might be necessary to generate XML where the key becomes an element name and the value becomes its content, like so:

<map>
  <key> VALUE </key>
  <key2> VALUE2 </key2>
 ...
</map>
Copy after login

Solution 1: Avoid Dynamic Element Names

It's generally advisable to avoid this type of XML generation because it introduces dependency on the map's content at runtime. This can impact interface contracts defined in the XML Schema (XSD).

Instead, consider using an enumerated type as the key of the Map to ensure that element names are known at compile time, allowing JAXB to generate a schema that restricts elements in the XML.

Solution 2: Customizing the XML Structure

To simplify the default generated structure to something like:

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>
Copy after login

Implement a custom MapAdapter that converts the Map into an array of MapElements.

The above is the detailed content of How to Marshal a Map into `value` Format in JAXB?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template