All of the web articles I've found about JSON seem to have to do with the specification of the data; I'm looking for tips on a lucid way to implement.
I have a persistent object that I get from Hibernate and a web service that is supposed to return a list of them.
The resulting JSON is supposed to include HATEOAS links mixed in with the data. And the JSON library should not fire any faults (resolve any proxies) but make them into href
attributes.
So, if I have 2 instances of Customer and a web service named /customers, I should get JSON that looks like this:
{
"href" : "/customers",
"data" : [ { "id" : 234,
"name" : "Bill Shatner",
"href" : "/customers/234",
"orders" : "/customers/234/orders",
"orders-count" : 2
},
{
"id" : 210,
"name" : "Malcolm Reynolds",
"href" : "/customers/210",
"orders" : "",
"orders-count" : 0
} ]
}
(NOTE: Just an illustration, not coded to any spec like HAL, etc.)
I feel like I'm having to hand-roll all this stuff in the service and that just feels like inexperience. Surely there's a proxy-aware web framework that would allow me to create a JSON template and pass it my domain objects and expect the right results?
@Path("/customers")
public HttpResponse getAllCustomers(HttpRequest req)
{
@Autowired CustomerRepository custRepo;
List<Customer> data = custRepo.findAll();
return ResponseBuilder.status(200).toJSON(data).build();
}
I understand this is probably more magic than possible, but surely there's something better than creating a HashMap
for each persistent object, hard-coding each getter into a put
and adding hard-coded href strings in a big galumphing loop?