SDN Controller Programming Guide
152
JSON Encoding
As described in previously the tasks a REST API normally accomplishes is decoding the request
and encode the result into the response. This sample application uses JSON [37] format but could
have used any other like XML. There are several different tools to assist on JSON conversion and
any tool and any way of organizing the codecs (or converters) could have been selected.
However, the HP VAN SDN Controller SDK offers some infrastructure classes and services with the
aim of unifying the way JSON codecs are implemented and shared. This example makes use of
such JSON API to implement a JSON codec for the Switch model object so it is used by the
SwitchResource.
Implementation of the JSON codecs is located at the hm-rs module; however for real applications
creating a new module to locate codecs might result in a better organization. The listing,
SwitchJsonCodec.java, shows the JSON codec for Switch (Defining Model Objects on page 119).
SwitchJsonCodec.java:
package com.hp.hm.rs.json;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hp.util.json.AbstractJsonCodec;
import com.hp.util.json.JsonCodec;
...
public class SwitchJsonCodec extends AbstractJsonCodec<Switch> {
private static final String ID = "id";
private static final String MAC_ADDRESS = "mac_address";
private static final String IP_ADDRESS = "ip_address";
private static final String FRIENDLY_NAME = "friendly_name";
private static final String ACTIVE_STATE = "active_state";
public SwitchJsonCodec() {
super("switch", "switches");
}
@Override
public Switch decode(ObjectNode node) {
validateMandatoryFields(node, MAC_ADDRESS);
MacAddress macAddress = MacAddress.valueOf(
node.get(MAC_ADDRESS).asText());
Id<Switch, Long> id = null;
if (!node.path(ID).isMissingNode()) {
id = Id.valueOf(Long.valueOf(node.get(ID).asLong()));
}
Switch device = new Switch(id, macAddress);