How to create a json from my object?

Asked

Viewed 278 times

3

I have a Product object that I can’t turn into json using json_encode:

<?php
class Produto {
    public $nome;
    public $preco;
    public $descricao;

    function transformarJson(){
    }

}

?>

How can I do that?

  • How you are using json_encode?

  • Putz Yure Pereira ! Thank you so much for your help ! I’m studying programming now, thanks by force !

1 answer

2


You can do this as follows below, in the example I am using the native PHP function json_encode that transforms an object to the format json, but in case you want to do the reverse, you can also use the function json_decode:

<?php
class Produto {

    public $nome;
    public $preco;
    public $descricao;

    public function transformarJson(){

        return json_encode($this);

    }
    // Não consigo transformar meu objeto Produto em json usando json_encode

}

$produto = new Produto();

$produto->nome = 'Celular';
$produto->preco = 'R$ 1010,00';
$produto->descricao = 'Celular';

var_dump($produto->transformarJson());

Upshot:

string(46) "{"nome":"Test","preco":"test","descricao":"e"}" 

Test the code here

Browser other questions tagged

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