Numbers Return As Strings In Rest Json

Currently when I return found model using yii2 REST api it can’t detect type of the field exactly and returns numbers as strings, like:


  "name": "New plan name",

  "created": 1386247539,  //integer

  "amount": "2000", //unsigned integer

  "currency": "usd",

  "object": "plan",

  "latitude": "90.123123", //decimal

  "interval_count": "1",

  "trial_period_days": null,


What is the best way to automatically convert strings to numbers?

Why not typecast them?

If you expect an integer (int)$var if you expect a double/float (float)$val, same goes for stings with (string) and boolean values with (bool) etc.

You could also do a is_numeric() check before typecasting for instance.

You can also use (float) for whole numbers and for decimals.

Dunno if yii2 has a afterFind method, but if it does, that’s the place where you could do the conversion.

Yes afterFind will work, but this conversion will be applied to all application, not just for api. Maybe there is a better place for this logic, like extending yii/rest/Serializer or something else?

If i understand correctly you do this in a model, so why not have a base model from where all your models extend and in that base model override the afterFind method so that it will be inherited by other models and would ease your work.

In 1.1 you would simple extend CactiveRecord into a ActiveRecord and all your models would inherit ActiveRecord. In yii2 things should be pretty similar (not the class but the procedure).

Also, yii2 has a dependency injection mechanism, maybe that does help, i really have no idea honestly since i haven’t tried it yet.

Yii2 AR already does typecasting if possible. For unsigned integers and floating numbers, they are kept as strings to preserve precision. You can override fields() method to typecast these types if you want.