Jmsserializerbundle: Serializing a stdClass

Created on 9 Aug 2012  路  9Comments  路  Source: schmittjoh/JMSSerializerBundle

Somebody in IRC mentioned this, so figured I'd try it out too.

It seems the bundle doesn't serialize a stdClass. Is there a reason why? (I'm clueless as to the inner workings of JMSSerializer)

$object = new \stdClass();
$object->foo = 'foo';
$object->bar = 'bar';
echo $serializer->serialize($object, 'json');
serializer issue

Most helpful comment

In 2016, i continue having this issue

All 9 comments

I guess stdClass should just be cast to an array.

Related: https://github.com/schmittjoh/JMSSerializerBundle/issues/271

A stdClass by itself doesn't seem to be a problem as you really have few other ways, if any, to serialize them, but it seems other objects are treated similarly.

@lsmith77
Casting stdClass to array converts empty objects to empty arrays. so, no good

I agree.

Imo:

$aObj = new \StdClass();
$aObj->foo = "bar";
$aObj->fus = ["roo" => "da"];

$bObj = new \StdClass();

$arr = [
    [
       "bar" => "a",
       "obj" => $aObj,
    ],
    [
       "bar" => "a",
       "obj" => $bObj,
    ],
]

Should result in:

[
  {
    "bar": "a",
    "obj": {
       "foo": "bar",
       "fus": {
         "roo": "da"
       } 
    }
  },
  {
   "bar": "b",
   "obj": {}
  }
]

This is not possible at the moment as far as I can see

In 2016, i continue having this issue

2017 and still banging our heads against a brick wall.

@fracz @skonsoft

commented about it already here

As already said, stdclass is an php particularity and different developers handle data inside it in different ways and because of it, there is no "true" way to solve the problem.

Even phpitself handles it in a particular way and having edge cases that was necessary to document
http://php.net/manual/en/language.types.object.php#language.types.object.casting

An array converts to an object with properties named by keys and corresponding values, with the exception of numeric keys which will be inaccessible unless iterated.

I understand that there are more than 5-10 issues about stdClss, but IMO the solution is simple:

  • get rid of stdClass in your code
  • implement this class handler in a user package

A custom handler as suggested in https://github.com/schmittjoh/serializer/pull/429 can be a solution for you, since you can decide the solution to adopt that fits in a better way your application.

In case I'm missing some important details, or you do not agree with my explanation can you explain your usecase?

@goetas Thanks, I got rid of stdClass in my code and I deal with a simple array instead.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

grimabe picture grimabe  路  6Comments

kevinpapst picture kevinpapst  路  6Comments

CsabaNa picture CsabaNa  路  3Comments

Chrysweel picture Chrysweel  路  7Comments

tcardonne picture tcardonne  路  3Comments