json_decode 到自定义类
是否可以将 json 字符串解码为 stdClass 以外的对象?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
是否可以将 json 字符串解码为 stdClass 以外的对象?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(16)
您可以通过以下方式做到这一点..
?>
欲了解更多详情,请访问
create-custom-class-in-php-from- json 或数组
You can do it in below way ..
?>
For more details visit
create-custom-class-in-php-from-json-or-array
您可以为您的对象创建一个包装器,并使包装器看起来就像对象本身一样。它将适用于多级对象。
You can make a wrapper for your object and make the wrapper look like it is the object itself. And it will work with multilevel objects.
使用 反射:
Use Reflection:
不,从 PHP 5.5.1 开始这是不可能的。
唯一可能的是
json_decode
返回关联数组而不是 StdClass 对象。No, this is not possible as of PHP 5.5.1.
The only thing possible is to have
json_decode
return associate arrays instead of the StdClass objects.正如戈登所说,这是不可能的。但是,如果您正在寻找一种方法来获取可以解码为给定类实例的字符串,您可以使用 序列化 并反序列化。
As Gordon says is not possible. But if you are looking for a way to obtain a string that can be decoded as an instance of a give class you can use serialize and unserialize instead.
我曾经为此目的创建了一个抽象基类。我们将其称为 JsonConvertible。它应该对公共成员进行序列化和反序列化。使用反射和后期静态绑定可以实现这一点。
只是凭记忆,所以可能并不完美。您还必须排除静态属性,并且可能会为派生类提供在序列化到 json 或从 json 序列化时忽略某些属性的机会。尽管如此,我希望你能明白。
I once created an abstract base class for this purpose. Let's call it JsonConvertible. It should serialize and deserialize the public members. This is possible using Reflection and late static binding.
Just from memory, so probably not flawless. You will also have to exclude static properties and may give derived classes the chance to make some properties ignored when serialized to/from json. I hope you get the idea, nonetheless.
JSON 是一种在各种编程语言之间传输数据的简单协议(它也是 JavaScript 的子集),仅支持某些类型:数字、字符串、数组/列表、对象/字典。对象只是键=值映射,数组是有序列表。
所以没有办法以通用的方式表达自定义对象。解决方案是定义一个结构,您的程序将知道它是一个自定义对象。
这是一个示例:
这可用于创建
MyClass
的实例并将字段a
和foo
设置为123
和“栏”
。JSON is a simple protocol to transfer data between various programming languages (and it's also a subset of JavaScript) which supports just certain types: numbers, strings, arrays/lists, objects/dicts. Objects are just key=value maps and Arrays are ordered lists.
So there is no way to express custom objects in a generic way. The solution is defining a structure where your program(s) will know that it's a custom object.
Here's an example:
This could be used to create an instance of
MyClass
and set the fieldsa
andfoo
to123
and"bar"
.我继续将 John Petit 的答案实现为一个函数(gist):
这非常适合我的用例。然而,Yevgeniy Afanasyev 的回应对我来说似乎同样有希望。可以让你的类有一个额外的“构造函数”,如下所示:
这也是受到这个答案的启发。
编辑:我已经使用 karriereat/json-decoder 一段时间了,我已经绝对没问题。它是轻量级的并且非常容易扩展。 这是我编写的用于将 JSON 反序列化为 Carbon/CarbonImmutable 对象的绑定示例。
I went ahead and implemented John Petit's answer, as a function(gist):
This worked perfectly for my use case. However Yevgeniy Afanasyev's response seems equally promising to me. It could be possible to have your class have an extra "constructor", like so:
This is also inspired by this answer.
EDIT: I have been using karriereat/json-decoder for some time now, and I have had absolutely no trouble with it. It is lightweight and very easily extensible. Here's an example of a binding I wrote to deserialize JSON into a Carbon/CarbonImmutable object.
这对我有用,特别是如果目标类中没有设置器或命名属性
This worked for me, especially for if you don't have setters or named properties in the target class
不直接,但如果类有一个参数名称与 JSON 对象中的键匹配的构造函数,您可以简单地将 JSON 解码为关联数组,然后通过“...”(参数解包)运算符将其传递给构造函数:
输出:
然而,在实践中,经常需要做一些额外的映射,特别是也需要递归解码的子对象。因此,通常最好在每个类中有一个静态
fromArray
函数,在将结果传递给构造函数之前预处理 json 解码的数组:Not directly, but if the class has a constructor with parameter names that match the keys in the JSON object, you can simply decode the JSON into an associative array and pass it to the constructor via the '...' (argument unpacking) operator:
Output:
However, in practice, there is often some additional mapping to do, especially sub-objects that need to be recursively decoded too. So usually it is better to have a static
fromArray
function in each class that pre-processes the json-decoded array before passing the result to the constructor:所有这些都激发了我对通用函数的灵感:
在类声明中调用:
All this here inspired me to a generic function:
to be called in class declaration:
不是自动的。但你可以按照老式的路线来做。
或者,您可以使其更加自动化:
编辑:变得更奇特:
Not automatically. But you can do it the old fashioned route.
Or alternatively, you could make that more automatic:
Edit: getting a little fancier:
我们构建了 JsonMapper 来自动将 JSON 对象映射到我们自己的模型类上。它适用于嵌套/子对象。
它仅依赖于文档块类型信息进行映射,大多数类属性无论如何都有:
We built JsonMapper to map JSON objects onto our own model classes automatically. It works fine with nested/child objects.
It only relies on docblock type information for mapping, which most class properties have anyway:
你可以做到——这是一个拼凑,但完全有可能。当我们开始将东西存储在沙发底座中时,我们必须这样做。
在我们的基准测试中,这比尝试迭代所有类变量要快得多。
警告:不适用于 stdClass 之外的嵌套对象
编辑:请记住数据源,强烈建议您不要在没有仔细分析风险的情况下使用来自用户的不受信任的数据执行此操作。
You can do it - it's a kludge but totally possible. We had to do when we started storing things in couchbase.
In our benchmarks this was way faster than trying to iterate through all the class variables.
Caveat: Won't work for nested objects other than stdClass
Edit: keep in mind the data source, it's strongly recommended that you don't do this withe untrusted data from users without a very carful analysis of the risks.
您可以使用 Johannes Schmitt 的序列化程序库。
在最新版本的 JMS 序列化器中,语法为:
You could use Johannes Schmitt's Serializer library.
In the latest version of the JMS serializer the syntax is:
我很惊讶还没有人提到这一点。
使用 Symfony 序列化器组件: https://symfony.com/doc/current/components/serializer .html
从对象序列化为 JSON:
从 JSON 反序列化为对象: (本示例使用 XML 只是为了演示格式的灵活性)
I'm surprised no one mentioned this, yet.
Use the Symfony Serializer component: https://symfony.com/doc/current/components/serializer.html
Serializing from Object to JSON:
Deserializing from JSON to Object: (this example uses XML just to demonstrate the flexibility of formats)