Search code examples
phpjsonsymfonyserializationjms-serializer

Is it possible to serialize an array to the root of an object with JMS Serializer?


Imagine I have a simple object, structured similarly to the one below:

Object (SomeClass) {
    $someOtherData (array) [
        ...
    ]

    $data (array) [
        "key": "value",
        "key": "value",
        "key": "value",
        "key": "value"
    ]
}

If I were to serialize this object with JMS Serializer to JSON, I'd get a result that has an identical structure, but with $data being on the root element, like so:

{
    "someOtherData": {
        ...
    },
    "data": {
        "key": "value",
        "key": "value",
        "key": "value",
        "key": "value"
    }
}

I need to have the content of the $data variable be on the root of the serialized result, i.e:

{
   "someOtherData": {
       ...
   },
   "key": "value",
   "key": "value",
   "key": "value",
   "key": "value"
}

Is this possible? If so, how?


Solution

  • Turns out there is an annotation for this. It's the @Inline annotation:

    use JMS\Serializer\Annotation\Inline;
    
    // ...
    
    /**
     * @var array
     *
     * @Inline
     */
    protected $variables;