convert json to php object

Asked

Viewed 2,965 times

3

UPDATE

I found this answer from Soen, on the link suggested by @Pedrox, talks about Reflection, would be applicable to this case as well?


As I have been told here on Sopt, i was trying to convert a list of objects to json. Well, now I need to recover this list from json to an array of objects.

The problem is that the json_decode, as it says to documentation, me 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 a list of objects, similar to the functions serialize and unserialize do. I saw in this topic that in java has how to do this, passing the json and the POJO class of the custom object for a lib method Gson, and it converts automatically, and also that I can do this using a foreach or for.

It is possible to retrieve my Current, Save and Special json objects in a similar way to java?

  • The problem you have is you can’t call the methods sacar(), depositar(), cobrarTarifa() for example?

  • @rray did not understand, how so?

  • For example if you do a foreach and inside it call the sacar() regardless of account type, does it work? or error?

  • @rray believe so, because in the foreach I would have to keep giving new in the object according to the type and setting the attributes in the constructor.

4 answers

1

If I understand correctly, you want to turn the json generated array into Object. I would make this two ways:

$json = (object) $json;

or

foreach ($a as $key => $value) {
    $objeto->$key = $value;
}
  • I thought about it, however, the array(or json) stores different objects, see in the code I posted. Current, Special, Save are different objects.

  • 2

    "do" -> do

1

That way it works: https://stackoverflow.com/a/3243949/4566483

In the "arrayToObject" function in the first parameter vc passes 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());
  • You could put the function code in your answer?

  • The conversion sounds very interesting, but I don’t understand what is being done in the code, if you or someone who knows English can translate part of the answer, it would be nice.

1


I thank you all for your 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 the ReflectionClass does not bring inherited properties directly. Instead of working with json in the form of array associative(json_decode($file, true)), I preferred to leave as objects stdClass for making it easier for me to treat attributes in a more general way.

Man json decoded stayed that 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, being the last two inherited from the first), the interface is implemented Jsonserializable as well as its mandatory method, and in it I create an array containing all class attributes(via jsonSerialize()) and, when necessary, bring the methods of the ancestral classes also, calling the same method(parent::jsonSerialize()).

In the end, my class was 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;
        }
    }

}

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

  • The problem is that I need to return the json to my Save, Chain and Special objects (has a link from another question with the classes in the text). However, there are inheritances between classes and all inherit from Account, so they share attributes.

  • From what I saw in the other question, you’re trying to generate a json of private attributes. Only the use of json is public. For this use: http://php.net/manual/en/class.jsonserializable.php

  • Ivan, the other question is solved precisely with the use of jsonserializable, see my reply there, only that the site only allows to mark my answer as the correct one after 2 days. Convert my objects to json I managed using this interface. Now I need to do the reverse. It seems that it is possible to do this using Reflection but I do not know much this method.

  • see if this helps you: https://3v4l.org/vvv2g/bytecode

  • I’ll try the code here.

  • I honestly couldn’t even implement this class into my :/

  • I edited the question, I hope you solved it. Now Using Reflection. As you had commented.

  • Thanks for the help, but actually I need to do the reverse, Code in json for object. But your code already gave me a basis to do that, I’ll try here.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.