Rest API: return Strings only


(Stefano Mtangoo) #1

I have a problem with REST API. The return value consists of Integers and Numbers. I know that is common sense but I want all my fields in JSON to be strings not their natural value. Is there a setting to disable converting values to their natural type and remain strings only?

TIA


(Yiiframework) #2

See "Controlling JSON output" here:

http://www.yiiframework.com/doc-2.0/guide-rest-response-formatting.html#data-serializing

JSON_NUMERIC_CHECK might help:

http://php.net/manual/en/json.constants.php


(Stefano Mtangoo) #3

Thanks a lot. I use AR for this specific case and docs there says

I hope that means it automagically adds the JSON_NUMERIC_CHECK to encode options (though not explicitly said I think it is implied). So will overriding the encodeOptions help in this case? I mean something like this, will it work?




'response' => [

	'formatters' => [

    	\yii\web\Response::FORMAT_JSON => [

        	'class' => 'yii\web\JsonResponseFormatter', 

        	'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, //No JSON_NUMERIC_CHECK here

    	],

	],

],




(Yiiframework) #4

Don’t know, but sounds worth a try :wink: