Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

后端 未结 4 1975
旧时难觅i
旧时难觅i 2020-11-28 04:52

I am developing a web application in PHP,

I need to transfer many objects from server as JSON string, is there any library existing for PHP to convert object to JSON

4条回答
  •  猫巷女王i
    2020-11-28 05:17

    This should do the trick!

    // convert object => json
    $json = json_encode($myObject);
    
    // convert json => object
    $obj = json_decode($json);
    

    Here's an example

    $foo = new StdClass();
    $foo->hello = "world";
    $foo->bar = "baz";
    
    $json = json_encode($foo);
    echo $json;
    //=> {"hello":"world","bar":"baz"}
    
    print_r(json_decode($json));
    // stdClass Object
    // (
    //   [hello] => world
    //   [bar] => baz
    // )
    

    If you want the output as an Array instead of an Object, pass true to json_decode

    print_r(json_decode($json, true));
    // Array
    // (
    //   [hello] => world
    //   [bar] => baz
    // )    
    

    More about json_encode()

    See also: json_decode()

提交回复
热议问题