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

2

7

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?

Claycomb answered 10/9, 2014 at 11:22 Comment(0)
C
9

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

use JMS\Serializer\Annotation\Inline;

// ...

/**
 * @var array
 *
 * @Inline
 */
protected $variables;
Claycomb answered 10/9, 2014 at 13:34 Comment(0)
R
0

I think the best method is using a SerializationHandler. Here you can find a bit of documentation: http://jmsyst.com/libs/serializer/master/handlers.

Ripp answered 10/9, 2014 at 12:3 Comment(3)
Hmmm, I have been trying that since I posted this question - only thing is, I keep getting 'null' as the result of the serialization, no matter what I return from the handler. Weird...Claycomb
could you create a gist with object class file and SerializerHandler?Ripp
Nevermind! I found exactly what I was after. The @Inline annotation.Claycomb

© 2022 - 2024 — McMap. All rights reserved.