JsonSerializable

本文介绍了PHP中如何使用JSON进行数据交换,包括基本的json_encode使用方法及如何处理复杂对象。通过实现JsonSerializable接口,可以自定义对象的JSON序列化方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON is the modern data format used in "AJAX" applications. As the leading language for the Web PHP course has support for handling JSON data: You can pass any data to json_encode() and the function will create a JSON representation of this data:

[php]

<?php
echo json_encode(array(1,2,3,4));
?>

[1,2,3,4]
[/php]

This also works for objects:

[php]

<?php
$o = new stdclass;
$o->a = 42;
echo json_encode($o);
?>

{"a":42}
[/php]

Wonderful. But the world isn't that easy. For many PHP objects the JSON-representation of the data is a bit more complex.for instance what about private properties or maybe you want to calculate some inner values? - In PHP 5.3 you were on your own. but thanks to Sara there's hope in sight: the new interface JsonSerializable. Classes implementing this interface have to provide a method jsonSerialize() which will be called by json_encode() and has to return a JSON-compatible representation of the data by doing whatever you want. So let's take a look:

[php]

<?php
class JsonTest implements JsonSerializable {
    private $a, $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function jsonSerialize() {
        return $this->a + $this->b;
    }
}

echo json_encode(new JsonTest(23, 42));
?>

65
[/php]

Now this example in itself is of course useless, but let's create a bigger structure, which includes a few of these objects:

[php]

<?php
$data = array(
    new stdClass();
    new JsonTest(1,2),
    new JsonTest(3,4),
    array(5,6)
);
echo json_encode($data);
?>

[{},3,7,[5,6]]

[/php]

Of course you'd usually have more complex serialization logic, but that's left to you.

Now almost certainly somebody will ask "and what about the other way round?" - The only answer there is: Sorry there we can't do much. JSON doesn't encode and meta-information so our generic parser in json_decode() can't do anything special. But anyways: The new interface will certainly be useful.



转载于:https://my.oschina.net/clearchen/blog/112974

### 解决Python中对象不可JSON序列化的错误 当遇到`Object of type 'ndarray' is not JSON serializable`这样的错误提示时,表明正试图将一个不支持JSON序列化的对象转换成JSON格式[^1]。对于这种类型的错误,有几种常见的方式可以解决问题。 #### 方法一:使用Numpy自带函数处理Ndarray 如果问题是由于NumPy数组引起的,则可以直接利用NumPy库提供的`.tolist()`方法将其转化为列表形式再进行序列化操作。 ```python import numpy as np arr = np.array([1, 2, 3]) json_str = json.dumps(arr.tolist()) print(json_str) ``` #### 方法二:自定义Encoder子类 通过继承`json.JSONEncoder`并重写其`default()`方法来自定义编码逻辑,使得特定类型的对象能够被正确地转为JSON格式[^4]。 ```python from datetime import date import json class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (date)): # 可以扩展更多类型判断条件 return str(obj) elif hasattr(obj,'to_dict'): return obj.to_dict() return super().default(obj) data_with_date = {"today": date.today()} custom_encoded_json = json.dumps(data_with_date, cls=CustomEncoder) print(custom_encoded_json) ``` #### 方法三:实现ToDict接口 让待序列化的类拥有返回字典表示的方法(如`to_dict()`),之后就可以很容易地把复杂的数据结构映射到简单的键值对上以便于JSON化[^3]。 ```python class Person: def __init__(self,name,age): self.name=name self.age=age def to_dict(self): return { "name":self.name, "age":self.age } person_instance = Person("Alice",30) dict_data = person_instance.to_dict() json_string = json.dumps(dict_data) print(json_string) ``` 以上三种方式均能有效应对不同场景下的对象不可JSON序列化问题,在实际应用过程中可根据具体需求选取最合适的解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值