Attribute-driven static JSON codec generation for MoonBit
///|
#custom.serde(rename_all="camelCase")
struct Profile {
display_name : String
#custom.serde(skip_serializing_if="Option::is_none")
avatar_url : String?
}///|
test "encode a profile without an avatar" {
let profile : Profile = @json.from_json({ "displayName": "Aki" })
assert_eq(ToJson::to_json(profile), { "displayName": "Aki" })
}[!NOTE] These instructions apply to the published release. Serde is not yet available on Mooncakes.
moon add totto2727/serdemoonx totto2727/serde-gen --help
nix run github:totto2727-org/serde -- --helpnix profile add github:totto2727-org/serde{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
serde.url = "github:totto2727-org/serde";
};
outputs = { nixpkgs, serde, ... }:
let
system = "aarch64-darwin";
pkgs = import nixpkgs {
inherit system;
overlays = [ serde.overlays.default ];
};
in
{
devShells.${system}.default = pkgs.mkShell {
packages = [ pkgs.serde-gen ];
};
};
}import {
"moonbitlang/core/json",
"totto2727/serde",
}
rule(name: "serde", command: "moonx totto2727/serde-gen $input --output $output")
dev_build(rule: "serde", input: "models.mbt", output: "models.generated.mbt")fn deny_unknown(fields : Map[String, Json], allowed : Array[String], path : DecodeContext) -> Unit raise JsonDecodeErrorfn deny_unknown_paths(fields : Map[String, Json], paths : Array[Array[String]], path : DecodeContext) -> Unit raise JsonDecodeErrorfn discriminator(fields : Map[String, Json], tag : String, path : DecodeContext) -> String raise JsonDecodeErrorfn field(fields : Map[String, Json], key : String, aliases : Array[String], path : DecodeContext) -> Json? raise JsonDecodeErrorfn read_path(fields : Map[String, Json], keys : Array[String], path : DecodeContext) -> (Json?, DecodeContext, String) raise JsonDecodeErrorfn[T] untagged(value : Json, path : DecodeContext, candidates : Array[(String, (Json, DecodeContext) -> T raise JsonDecodeError)]) -> T raise JsonDecodeError