在PHP中将对象转换为JSON和JSON为对象,(像Gson for Java这样的库) [英] Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

查看:119
本文介绍了在PHP中将对象转换为JSON和JSON为对象,(像Gson for Java这样的库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PHP中开发一个Web应用程序,我需要将许多对象从服务器转换为JSON字符串,是否存在任何用于将对象转换为PHP的库JSON和JSON String到Objec,就像Java的Gson库一样。

解决方案


$ b

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

//转换json =>对象
$ obj = json_decode($ json);

下面是一个例子

  $ 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
//)

如果您希望输出为数组而不是对象,请传递 true to json_decode

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

更多关于 json_encode()



另见: json_decode()


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 and JSON String to Objec, like Gson library for Java.

解决方案

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()

这篇关于在PHP中将对象转换为JSON和JSON为对象,(像Gson for Java这样的库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆