Deserialize Object in array after json_encode

Asked

Viewed 84 times

0

I have an array of objects.

But before sending these objects in the array, I do serialize() in each index of the array because they are objects:

function serialize(){
    return json_encode(get_object_vars ($this));
}   

Now I do json_encode in that array and send a request reply

Now I will recover that array on the reply page.

But I need to deserialize the objects

How to do this?

I’m getting the array like this:

Array
(
    [0] => {"id":1,"ordem":"20191213221255","status":"OS Finalizada","dataEntrada":"2019-10-13","cliente":1,"equipamento":1,"defeitoRelatado":"Aparelho n\u00e3o liga","estado":"P\u00c9SSIMO","aprovado":"N\u00e3o","garantia":"Sim","analiseTecnico":"bacana","composicaoOrcamento":null,"valorOrcamento":null,"pgtoEntrada":null,"pgtoFinal":null,"dataSaida":"2019-10-16 00:10:00","obs":null}
    [1] =>   ....
)

I’m trying like down but it didn’t work!

$ordensSerializadas = json_decode( listar ( $_SESSION["token"] ), true);

$ordens = array();

foreach ( $ordensSerializadas as $ordem )
     $ordens[] = $ordem->unserialize();

print_r ($ordens);

ERROR:

<br />
<b>Fatal error</b>:  Uncaught Error: Call to a member function unserialize() on string in D:\web\ctemcasb.com.br\acweb.php:156
Stack trace:
#0 {main}
  thrown in <b>D:\web\ctemcasb.com.br\acweb.php</b> on line <b>156</b><br />

How to solve this?

1 answer

4


JSON does not serialize the object, only represents as string the current state of the same. If you really want to serialize, you will have to use the functions serialize and unserialize, or third-party libraries that can do the analogous process.

If you want to keep JSON, you just treat it on the other side as JSON.

foreach ( $ordensSerializadas as $ordem )
     $ordens[] = json_decode($ordem);

But this can be directly influenced by the return of function listar, since you’ve already done the json_decode on it and it wouldn’t make much sense to process JSON for parts (maybe there’s more going wrong).

  • It was bad @woss, I saw that the answer was the same so delete mine.

  • 1

    @Lucasemanuel Ah, I saw that I ended up editing... I had given the -1 just for being wrong in the first version, not for answering the same thing.

  • blz, got it! That’s right! Thanks! !

Browser other questions tagged

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