Serializers & Formats
Serializers & Formats
Hateoas provides a set of serializers. Each serializer generates either XML or JSON content following a specific format, such as HAL, or Atom Links.
The JsonHalSerializer
The JsonHalSerializer is the default JSON serializer. HAL provides a
convention for expressing hypermedia controls using _links for links and
_embedded for embedded resources.

The HAL information model looks like this in JSON:
{
"message": "Hello, World!",
"_links": {
"self": {
"href": "/notes/0"
}
},
"_embedded": {
"associated_events": [
{
"name": "SymfonyCon",
"date": "2013-12-12T00:00:00+0100"
}
]
}
}
The XmlSerializer
The XmlSerializer generates
Atom Links in XML
documents. It is the default XML serializer.
<?xml version="1.0" encoding="UTF-8"?>
<note>
<message><![CDATA[Hello, World!]]></message>
<link rel="self" href="/notes/0"/>
</note>
The XmlHalSerializer
The XmlHalSerializer generates HAL-compliant XML using
resource elements and link elements:
<?xml version="1.0" encoding="UTF-8"?>
<resource href="/notes/0">
<message><![CDATA[Hello, World!]]></message>
<resource rel="associated_events">
<name><![CDATA[SymfonyCon]]></name>
<date><![CDATA[2013-12-12T00:00:00+0100]]></date>
</resource>
</resource>
Adding New Serializers
You can add new serializers by implementing either the
JsonSerializerInterface or the XmlSerializerInterface.
Each interface defines the methods needed to serialize links and embedded resources
in the respective format.
For JSON, implement the JsonSerializerInterface:
use Hateoas\Serializer\JsonSerializerInterface;
use JMS\Serializer\JsonSerializationVisitor;
class MyJsonSerializer implements JsonSerializerInterface
{
public function serializeLinks(array $links, JsonSerializationVisitor $visitor) {}
public function serializeEmbeddeds(array $embeddeds, JsonSerializationVisitor $visitor) {}
}
Then, register your custom serializer with the HateoasBuilder:
$hateoas = HateoasBuilder::create()
->setJsonSerializer(new MyJsonSerializer())
->build();