convert json to php object

3

UPDATE

I found this answer from SOen , at the link suggested by @Pedrox, talks about reflection , would it apply to this case too?

As I've already been told here in the SOpt , I was trying to convert a list of objects to json. Well, now I need to retrieve this json list for an array of objects.

The problem is that json_decode , as told to documentation , returns an array of a special object called stdObject or an associative array, in my case this:

Array
(
    [0] => Array
        (
            [Corrente] => Array
                (
                    [tarifaManutencao] => 12.5
                    [numero] => 123
                    [proprietario] => teste
                    [saldo] => 3.1
                    [permissoesEspeciaisHabilitadas] => 
                )

        )

    [1] => Array
        (
            [Poupanca] => Array
                (
                    [quantidadeConsultas] => 0
                    [numero] => 456
                    [proprietario] => testeprop
                    [saldo] => 50
                    [permissoesEspeciaisHabilitadas] => 
                )

        )

    [2] => Array
        (
            [Especial] => Array
                (
                    [limite] => 500
                    [valorEmprestado] => 0
                    [jurosCobrados] => 0
                    [tarifaManutencao] => 20
                    [numero] => 789
                    [proprietario] => teste4
                    [saldo] => 100
                    [permissoesEspeciaisHabilitadas] => 
                )

        )

)

What I needed was to return the array as an object list, similar to what the serialize and unserialize functions do. In this topic that java has to do this by passing json and POJO class I have a custom object for a method of lib Gson , and it automatically converts, and also that I can do this using a foreach or for .

Is it possible for me to retrieve my Current, Saved, and Json Special objects similar to java?

    
asked by anonymous 11.11.2015 / 14:33

4 answers

1

Thanks to everyone for the contribution, but after studying the suggestions and researching on reflection, I was able to create a json converter for my objects, including solving the attribute inheritance problem, since ReflectionClass does not have inherited properties directly . Instead of working with decode of json as% associative% ( array ), I preferred to leave as json_decode($file, true) objects because it makes it easier for me to treat attributes more generically.

My stdClass decoded was this way now:

array (size=3)
  0 => 
    object(stdClass)[3]
      public 'Especial' => 
        object(stdClass)[4]
          public 'limite' => int 500
          public 'valorEmprestado' => int 0
          public 'jurosCobrados' => int 0
          public 'tarifaManutencao' => int 20
          public 'numero' => int 789
          public 'proprietario' => string 'teste4' (length=6)
          public 'saldo' => int 100
          public 'permissoesEspeciaisHabilitadas' => boolean false
  1 => 
    object(stdClass)[5]
      public 'Poupanca' => 
        object(stdClass)[6]
          public 'quantidadeConsultas' => int 0
          public 'numero' => int 456
          public 'proprietario' => string 'testeprop' (length=9)
          public 'saldo' => int 50
          public 'permissoesEspeciaisHabilitadas' => boolean false
  2 => 
    object(stdClass)[7]
      public 'Corrente' => 
        object(stdClass)[8]
          public 'tarifaManutencao' => float 12.5
          public 'numero' => int 123
          public 'proprietario' => string 'teste' (length=5)
          public 'saldo' => float 3.1
          public 'permissoesEspeciaisHabilitadas' => boolean false

In each class (Account, Current and Savings, the latter two inheriting from the first), the # as well as its mandatory method, and in it I create an array containing all the attributes of the class (via json ) and, when necessary, I bring the methods of the ancestor classes as well, calling the same method ( jsonSerialize() ).

In the end, my class looked like this:

/**
 * Description of JSONToObject
 *
 * @author diego.felipe
 */
class JSONToObject {

    private $decodeJson;

    public function __construct($jsonFile) {
        if (file_exists($jsonFile)) {
            $strJson = file_get_contents($jsonFile);
            $this->decodeJson = json_decode($strJson);
            var_dump($this->decodeJson);
        }
    }

    public function getArrayObjects() {
        if (!is_null($this->decodeJson) && is_array($this->decodeJson)) {
            $lista = Array();
            foreach ($this->decodeJson as $stdClass) {
                $className = key($stdClass);
                $jsonObj = $stdClass->$className;
                $reflectionClass = new ReflectionClass($className);
                $instance = $reflectionClass->newInstanceWithoutConstructor();
                $allAttributes = Array();

                do {
                    $reflectionClassProperties = Array();
                    foreach ($reflectionClass->getProperties() as $classAttribute) {
                        $classAttribute->setAccessible(true);
                        $reflectionClassProperties[] = $classAttribute;
                    }
                    $allAttributes = array_merge($reflectionClassProperties, $allAttributes);
                } while ($reflectionClass = $reflectionClass->getParentClass());

                foreach ($allAttributes as $attribute) {
                    $attribute->setAccessible(true);
                    $attrName = $attribute->getName();
                    $attribute->setValue($instance, $jsonObj->$attrName);
                }
                $lista[] = $instance;
            }
            return $lista;
        } else {
            return null;
        }
    }

}
    
18.11.2015 / 18:59
1

If I get it right, you want to transform the array generated by json into an object. I would do this in two ways:

$json = (object) $json;

or

foreach ($a as $key => $value) {
    $objeto->$key = $value;
}
    
11.11.2015 / 14:36
1

That way it works: link

In the function "arrayToObject" in the first parameter you pass the return of json_decode ($ string, true) and in the second the string with the name of the class for which you need to cast.

Follow the example:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

class Pessoa {
  public $nome;
  public function __construct($nome) {
    $this->nome = $nome;
  }

  public function getNome(){
      return $this->nome;
  }
}

$jsonPessoa = '{"nome":"Fulano"}';

$objPessoa = arrayToObject(json_decode($jsonPessoa, true), "Pessoa");

var_dump($objPessoa->getNome());
    
11.11.2015 / 14:47
0

Try something like this and tell me what happened?

function json_encode_private($object) {
    $public = [];
    $reflection = new ReflectionClass($object);
    foreach ($reflection->getProperties() as $property) {
        $property->setAccessible(true);
        $public[$property->getName()] = $property->getValue($object);
    }
    return json_encode($public);
}

Reference: SOen
Documentation: PHP.Net

    
12.11.2015 / 12:48