1

Consider the following Java bean class:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ApiRequest {
    private String operation;
    private Map<String, String> params = new HashMap<>();

    SpeApiRequest(String op) {
        operation = op;
    }

    void addParam(String name, String value) {
        params.put(name, value);
    }

    String serializeXml() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("<%s>", operation));
        for (Entry<String, String> e: params.entrySet()) {
            sb.append(String.format("<%s>%s</%s>",
                e.getKey(), e.getValue(), e.getKey()));
        }
        sb.append(String.format("</%s>", operation));
        return sb.toString();
    }
}

One instance of this class looks like this:

ApiRequest req = new ApiRequest("Login");
req.addParam("USERNAME", "myuser");
req.addParam("PASSWORD", "mypasswd");

I want the serialized XML for this object to look like this:

<Login>
    <USERNAME>myuser</USERNAME>
    <PASSWORD>mypasswd</PASSWORD>
</Login>

Another instance is like this:

ApiRequest req1 = new ApiRequest("LIST");
req1.addParam("LIST_TYPE", "2");
req1.addParam("VISIBILITY", "1");
req1.addParam("INCLUDE_ALL_LISTS", "true");

The serialized XML for this object would look like this:

<LIST>
    <LIST_TYPE>2</LIST_TYPE>
    <VISIBILITY>1</VISIBILITY>
    <INCLUDE_ALL_LISTS>true</INCLUDE_ALL_LISTS>
</LIST>

As you see my class could have a variable number of parameters. The root element in the serialized XML takes name same as operation and the nested elements are from the map nested in the class, params.

Currently I am doing the XML serialization in a donkey way using the serializeXml() method as shown.

Is it possible to modify my class for JAXB to marshal the objects shown above to what I want?

Curious
  • 2,783
  • 3
  • 29
  • 45

0 Answers0