Format conversion
The conversion to and from JSON is done using a nim-json-serialization format. For each type used in the RPC method, a serialization declaration tells json_rpc how to convert it to JSON, either using defaults or by overriding readValue and writeValue.
json_rpc will recursively parse the Nim types in order to produce marshalling code. This marshalling code uses the types to check the incoming JSON fields to ensure they exist and are of the correct kind.
The return type then performs the opposite process, converting Nim types to JSON for transport.
Creating a JSON format flavor
The createJsonFlavor API accepts a flavor name and serialization options. The flavor can be passed to RPC method APIs and it will be used to convert the parameters and return value. In the following example the flavor is named RpcConv:
createJsonFlavor RpcConv,
automaticObjectSerialization = false,
automaticPrimitivesSerialization = true,
requireAllFields = false,
omitOptionalFields = true, # Skip optional fields==none in Writer
allowUnknownFields = true,
skipNullFields = true # Skip optional fields==null in Reader
Object serialization
In the above configuration automatic object serialization is disabled. This is to avoid unintentionally using the default serializer for objects that define a custom serializer. Object serialization can be enabled per object using useDefaultSerializationIn:
type
UserInfo* = object
name*: string
bio*: string
UserInfo.useDefaultSerializationIn RpcConv
Custom type serialization
It is possible to provide a custom serializer for a given type creating writeValue and readValue functions:
type
UploadData* = object
path*: string
public*: bool
proc readValue*(
reader: var RpcConv.Reader, value: var UploadData
) {.gcsafe, raises: [IOError, SerializationError].} =
let path = reader.readValue(string)
value = UploadData(path: path, public: false)
proc writeValue*(
writer: var RpcConv.Writer, value: UploadData
) {.gcsafe, raises: [IOError].} =
writer.writeValue value.path
Learn more about serialization in the nim-json-serialization documentation.