Tim Davidson
Tim Davidson

Reputation: 69

Jackson 2.x serialization of empty object as property

Using Jackson annotations, I need to create a Java POJO for the following object to send to a REST API. The api is expecting a list of tcp ports mapped to empty objects like this:

{
   "ExposedPorts": {
           "22/tcp": {},
           "80/tcp": {}
     }
}

Upvotes: 0

Views: 125

Answers (1)

Mohit
Mohit

Reputation: 1755

Use a nested map to achieve the desired result.

class Ports{

    private Map<String, Map<String, String>> ports = new HashMap<String, Map<String,String>>();

    public void addPort(String port){
        ports.put(port, new HashMap<String, String>());
    }

    public Map<String, Map<String, String>> getPorts() {
        return ports;
    }

    public void setPorts(Map<String, Map<String, String>> ports) {
        this.ports = ports;
    }
}

Test case

Ports p = new Ports();
p.addPort("22/tcp");
ObjectMapper om = new ObjectMapper();
om.writeValue(System.out, p); //Produce {"ports":{"22/tcp":{}}}

Upvotes: 1

Related Questions