github编辑

Output Format

Creating the Serialize Class

use Astral\Serialize\Serialize;
use DateTime;

class UserLoginLog extends Serialize {
    public string $remark,
    public DateTime $create_time;
}

class User extends Serialize {
    public string $name,
    public int $age,
    public UserLoginLog $login_log
}

// Create an object
$user = User::from([
    'name' => 'Jon',
    'age' => 30
], login_log: new UserLoginLog(remark:'Test Data',create_time: DateTime::createFromFormat('Y-m-d','2008-09-01')));

Outputting the Object

Outputting an Array

Outputting a JSON String

  1. The Serialize class implements JsonSerializable by default. Similar to a Laravel Controller you can directly return the object, and the framework will output the JSON information correctly

  2. By default, the JSON output from Serialize includes data code and message f you need to [replace/modify/add] these, please refer to the configuration information Response Data Structure Definition

Outputting JSON Information

  • You can use the API toJsonString

  • Alternatively, you can directly use json_decode

Setting Output Code/Message

Setting Custom JSON Outer Layer

withResponses can temporarily add or modify custom return information. To add global return information, you can configure it in the Response Data Structure Definition

Outputting JSON Without Outer Layer Information

UsewithoutResponseToJsonString to return JSON data containing only the object’s properties.

最后更新于