[TYPO3-mvc] Making JSON data from object
Claus Due
claus at wildside.dk
Thu Nov 15 17:51:06 CET 2012
> i tried to use the <fed:data.json /> viewhelper [1], but i also got only empty brackets...
>
> how do you create json from
>
> (a) Tx_Extbase_Persistence_QueryResult
> (b) Tx_YourExtension_Domain_Model_YourObject
Hi Roland,
Since you already have FED installed, there is a Service to do just this:
Tx_Fed_Service_Domain
Once injected, it provices $this->domainService->getValuesByAnnotation($object, $annotationName).
$annotationName defaults to 'json' which means that any property in your Model will be exported to JSON:
/**
* @var string
* @json
*/
protected $title;
You can of course choose any annotation name you prefer, but usually it's better to use the default. If you don't use argument 3 (the annotation value) on getValuesByAnnotation, the mere presence of the annotation is enough to trigger export your property.
The getValuesByAnnotation($object) also supports arrays which means that QueryResult and ObjectStorage are also supported. You simply need to convert them to an array first:
$this->domainService->getValuesByAnnotation($queryResultOrObjectStorage->toArray());
The returned value is always an array. If given a single Domain object, one associative array of exported property values is returned. If input is an array, a numeric indexed array of associative arrays of exported object's property values is returned.
Relational properties are supported; 1:1 is inserted as an associative sub-array, 1:n and m:n as numeric arrays filled with associative arrays.
Pro tip: use this Service and other annotations to provide different levels of details on the objects you export, fx:
@json simple
@json detailed
You can even go one step further and define fictional property names:
/**
* @var string
* @json simple
*/
protected $summary;
Even if the "summary" column does not exist in the DB, if you add a getter method - which for example truncates a very long body text or concatenates some fields, formats numbers etc) and name it "getSummary" then this getter method is called when you export values by annotation "json" with argument three (the annotation value) being "simple":
$this->domainService->getValuesByAnnotation($object, 'json', 'simple');
And I go on. The annotation value matching even supports multiple values:
/**
* @var string
* @json simple detailed
*/
protected $summary;
…which will export the value if the third argument is either "simple" or "detailed" - and naturally this is also supported on relational properties (use case: export JSON of only a main topic if "simple", but include its related comment records if exporting as "defailed"). Okay, that's enough of a mini manual for now!
Hope you enjoy ;)
See also: http://fedext.net/services/domain.html#getValuesByAnnotation
Cheers,
Claus
More information about the TYPO3-project-typo3v4mvc
mailing list