[TYPO3-mvc] Json View Output

Frank Krueger fkrueger-ml at mp-group.net
Thu Feb 24 08:00:10 CET 2011


Hi list,

...
> But probably better/nicer might be to create a jsonViewObject that's doing
> the conversion for you and sending suitable headers etc.

My current approach is to use a different page type in my TS-setup and let
the json response be built  by an utility class:

-- TS setup --
# *** ajax response (json)
jsonResponse = PAGE
jsonResponse {

	# *** type num
	typeNum = 123456789

	# *** no header code
	config {
		disableAllHeaderCode = true
		additionalHeaders = Content-type:application/json
		xhtml_cleaning = 0
		admPanel = 0
		no_cache = 1
	}

	# *** object
	20 < tt_content.list.20.myext_pi1
}


-- Classes/Utility/Json.php --
class Tx_MyExt_Utility_Json {
	/**
	 * converts a extbase object into a json object / array string
	 *
	 * @param object $object
	 * @return string the json object string
	 */
	public static function getJsonObject($object) {

		$objectArray = array();
		foreach($object as $objectItem) {
			$objectItemArray = array();
			foreach($objectItem->_getProperties() as $key =>
$value) {
				$objectItemArray[$key] =
utf8_encode($value);
			}
			array_push($objectArray, $objectItemArray);
		}
		
		// *** build json array
		$jsonArray = array(
			'success'=>'success',
			'message'=>'success', 
			'total' => count($object),
			'data' => $objectArray
		);
		
		// *** return json object array
		return json_encode($jsonArray);
	}
}

-- Controller / Action --
public function indexAction() {
	$myObjectArray  = $this->myRepository->findAll();
	return Tx_MyExt_Utility_Json::getJsonObject($myObjectArray  );
}


Cheers,
Frank



More information about the TYPO3-project-typo3v4mvc mailing list