Skip to content
Advertisement

Serialize/deserialize nested objects to JSON with type in PHP

I have classes that extends an abstract class. I need to create instances of these classes through a string – preferably JSON.

Many of the objects are nested, and many properties are private. I need a way to:

  1. Create a JSON string of the complete object (with private properties and nested objects – with their private properties).
  2. Create a new Object from a JSON string, with the correct type and all nested objects.

I guess it needs to be recursive.

I’m using namespaces that end up looking like crap if I just cast the object to an array.

I’m thinking of writing a parser, label the classes in my JSON strings and then hardcode a factory function for every class, but that would take a lot of time.

Advertisement

Answer

I suggest you to use php’s serialize function

In cases like this it’s better to use this function because it exists for this purpose: you can store the serialized string wherever you want and after unserializing it you will get back the original PHP object with all the properties

With JSON, as you said, you’ll have no clue of what class the object was (unless you store it manually as a string) and of course there will be all the problems related to the private properties

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement