Skip to content

84 JSON 值往返转换 ​

@Serializable 值具有受类型检查的 JSON 结构。toJson 编码字段,fromJson<Note> 解码回声明的类型,而不是留下动态数据树。

norm
import std.serialization.Serializable
import std.json.fromJson
import std.json.toJson

@Serializable()
value Note {
  String title
  Integer priority
}

main() {
  Note original = Note(title: "Learn Norm", priority: 2)
  String encoded = original.toJson()
  Note restored = encoded.fromJson<Note>()
  printLine(encoded)
  printLine(restored.title)
  printLine(restored.priority)
}

预期输出:

text
{"title":"Learn Norm","priority":2}
Learn Norm
2

动手试试:把 priority 改成 3,比较编码和解码后的值。

精确规则:JSON API。

Norm 0.25