Removing a nesting

The serializer derived automatically uses the same nesting structure as your type. If you need to reduce the levels of nesting, you can set the #[serde(flatten)] attribute to use fields without enclosing objects. In the previous example, we used the Range type from the standard library to set a range in which to generate a random value, but we also want to see the implementation details in the serialized data. To do this, we need the start and end fields of the Range. We added this attribute to the field to cut out the { "range": ... } level of the structure.

For enumeration, serde_derive uses a tag as the name of the object. For example, the following JSON-RPC contains two variants:

#[derive(Serialize, Deserialize)]
enum RpcRequest {
Request { id: u32, method: String, params: Vec<Value> },
Notification { id: u32, method: String, params: Vec<Value> },
}

The params field contains an array of any JSON values represented by the serde_json::Value type, we'll explore this type later in this chapter. If you serialize an instance of this struct, it will include the name of a variant. Consider the following, for example:

{ "Request": { "id": 1, "method": "get_user", "params": [123] } }

This request isn't compatible with the JSON-RPC specification (https://www.jsonrpc.org/specification#request_object). We can drop the enclosing object with the #[serde(untagged)] attribute and the struct becomes as follows:

{ "id": 1, "method": "get_user", "params": [123] }

After this change, this serialized data can be sent as JSON-RPC. However, if you still want to keep the variant value in a serialized data form, you have to use another approach, which is described in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.237.131