Replies: 1 comment
-
Thought of adding custom serializer and attach it to your rest controller? That way you can have granular control as to what you return |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
This is half a question and half a feature request.
I have an
ActiveRecord
where one of itsfields
is an array representing mapping from IDs to values. When this has values, it is serialized as a JSON object (e.g.{"1": "foo", "9": "bar"}
. When it is empty,yii\rest\Serializer
serializes it to an empty array[]
rather than an empty object{}
.You can't avoid this by casting the array to
(object)
- this seems to be expected behavior (see #12043 , #957 ).Right now, my solution is to:
EmptyModel
that holds no dataEmptyModel
ArrayHelper::toArray()
so thatEmptyModel
s are not serialized (see below)Arrayable::toArray()
to use my overridden version ofArrayHelper::toArray()
.This solution is rather ugly, but I haven't found a better way to do it - is there a pretty way to force a property of a model to always be serialized as an object rather than an array? If not, does anyone have an idea how that could be made possible?
Beta Was this translation helpful? Give feedback.
All reactions