f# - 将 F# 列表设置为 null 以进行序列化

标签 f# json.net

我将 F# 与使用 JSON.NET 库的 JSON 数据存储一起使用。我尝试尽可能使用 F# 结构和类型,但遇到了以下问题。假设我希望存储以下数据结构,

type A = {
    id : int
    name : string
    posts : string list
}

创建工作正常,但要仅更新存储的 name 字段,我需要发送一个省略 posts 字段的 JSON 记录。使用空列表将不起作用,因为持久性系统会假定我希望用空列表替换现有帖子,从而覆盖它们。来自JSON.NET docs我读过一个字段可以通过将其设置为 null 来从序列化中省略,

let updatedEntry = { id : 0, name : "Fred", posts = null }

但是 F# 编译器会给出一个错误,指出类型 list 不能设置为 null。无论如何可以从 F# 中完成此操作,也许是我不知道的属性?谢谢

最佳答案

有两种方法可以轻松做到这一点:

选项 1

使用System.Collections.Generic.List类型,可以为null:

> type A = {id: int; name:string; posts: System.Collections.Generic.List<string> };;

type A =
  {id: int;
   name: string;
   posts: System.Collections.Generic.List<string>;}

> let a = {id=5; name="hello"; posts=null};;

val a : A = {id = 5;
             name = "hello";
             posts = null;}

选项 2

另一种更惯用的方式是使用 Option 类型:

> type A = {id: int; name:string; posts: string list option };;

type A =
  {id: int;
   name: string;
   posts: string list option;}

> let a = {id=5; name="there"; posts=None};;

val a : A = {id = 5;
             name = "there";
             posts = null;}

请注意,您会将 posts 成员与 None 进行比较,而不是将其与 null 进行比较。

随手阅读:Option types


编辑

(经过一些搜索和实验)您可以使用装箱来仍然使用 F# 类型作为值:

> type A = {id: int; name:string; posts: System.Object };;

type A =
  {id: int;
   name: string;
   posts: Object;}

> let a = {id=5; name="foo"; posts=null};;

val a : A = {id = 5;
             name = "foo";
             posts = null;}

> let b = {id=6; name="bar"; posts=(box [])};;

val b : A = {id = 6;
             name = "bar";
             posts = [];}

但我个人会坚持使用 Option 类型

关于f# - 将 F# 列表设置为 null 以进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750267/

相关文章:

.net - 如何解决 "System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized"

recursion - 我如何表达阶乘 n!使用 F# 函数,递归还是其他方式?

c# - 使用 Newtonsoft JSON 的 ObjectCreationHandling 的说明?

c# - 使用 Json.Net 序列化为键值字典?

f# - 访问 DU 成员的命名字段

f# - 如何使用单根对简单层次结构进行建模

c# - 在 F# 中使用 C# 流利库

C# JsonConvert 使用默认转换器而不是自定义转换器

C# Newtonsoft JSON - 使用未知对象集合反序列化对象

F# WebApi 从可区分联合返回格式正确的 json