Java Hypermedia Client

Posted on 27 Jul 2013 by Eric Oestrich

Recently I’ve been working on an Android app that uses a hypermedia API. This has presented some challenges because the JSON library I’m using turns JSON into java objects. Using a HashMap is out because you get into generic hell land.

Up until now I haven’t had to make a hypermedia client in anything but ruby. In ruby it’s very simple because the JSON you receive from the server gets turned into a hash. I think I have come across a nice way to get around it in java though.

Below are my java objects that Jackson parses into.

public class Link {
    @JsonProperty("href")
    public String href;
}
HalRoot
public class HalRoot {
    @JsonProperty("_links")
    protected RootLinks links;

    public String getSelfLink() {
        return links.self.href;
    }

    public String getOrdersLink() {
        return links.orders.href;
    }

    public class RootLinks {
        @JsonProperty("self")
        Link self;
        @JsonProperty("http://example.com/rels/orders")
        Link orders;
    }
}
HalOrders
public class HalOrders {
    @JsonProperty("_embedded")
    protected Embedded embedded;

    @JsonProperty("_links")
    protected Links links;

    public List<HalOrder> orders() {
        return embedded.orders;
    }

    public class Embedded {
        @JsonProperty("orders")
        List<HalOrder> orders;
    }

    public class Links {
        @JsonProperty("self")
        Link self;
    }
}
HalOrder
public class HalOrder {
    @JsonProperty("_embedded")
    protected Embedded embedded;

    @JsonProperty("_links")
    protected Links links;

    public List<HalItem> getItems() {
        return embedded.items;
    }

    public String getSelfLink() {
        return links.self.href;
    }

    public String getItemsLink() {
        return links.items.href;
    }

    public class Embedded {
        @JsonProperty("items")
        List<HalItem> items;
    }

    public class Links {
        @JsonProperty("self")
        Link self;
        @JsonProperty("http://nerdwordapp.com/rels/items")
        Link items;
    }
}
HalItem
public class HalItem {
    @JsonProperty("name")
    public String name;
}
comments powered by Disqus
Creative Commons License
This site's content is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License unless otherwise specified. Code on this site is licensed under the MIT License unless otherwise specified.