JSON 选项类型的序列化
JSON serialization for option types
我 运行 在为 JSON.
序列化时定义选项类型的字段时遇到了一个问题
之前 工作(没有选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string
}
After 抛出错误(带选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string option
}
method threw exception:
System.Runtime.Serialization.SerializationException: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
相关代码
let response = request.GetResponse() :?> HttpWebResponse
use reader = new StreamReader(response.GetResponseStream())
use memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(reader.ReadToEnd()))
let result = (new DataContractJsonSerializer(typeof<Article>)).ReadObject(memoryStream) :?> Article
这是一个可以为 null 的定义 int
。无数的 Null 引用异常证明 String 已经可以为 null...
open System
[<DataContract>]
type Person2 = {
[<DataMember(Name="Name") >]
entityName: Nullable<int>
[<DataMember(Name="Type") >]
entityType: String
}
但是,如果您打算用一堆空值填充它,也许您应该考虑 class。这真的很可怕,但它看起来是这样的:
let p1 = { entityName = Nullable(10); entityType = "John"}
let p2 = { entityName = System.Nullable(); entityType = null}
val p1 : Person2 = {entityName = 10;
entityType = "John";}
val p2 : Person2 = {entityName = null;
entityType = null;}
我 运行 在为 JSON.
序列化时定义选项类型的字段时遇到了一个问题之前 工作(没有选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string
}
After 抛出错误(带选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string option
}
method threw exception: System.Runtime.Serialization.SerializationException: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
相关代码
let response = request.GetResponse() :?> HttpWebResponse
use reader = new StreamReader(response.GetResponseStream())
use memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(reader.ReadToEnd()))
let result = (new DataContractJsonSerializer(typeof<Article>)).ReadObject(memoryStream) :?> Article
这是一个可以为 null 的定义 int
。无数的 Null 引用异常证明 String 已经可以为 null...
open System
[<DataContract>]
type Person2 = {
[<DataMember(Name="Name") >]
entityName: Nullable<int>
[<DataMember(Name="Type") >]
entityType: String
}
但是,如果您打算用一堆空值填充它,也许您应该考虑 class。这真的很可怕,但它看起来是这样的:
let p1 = { entityName = Nullable(10); entityType = "John"}
let p2 = { entityName = System.Nullable(); entityType = null}
val p1 : Person2 = {entityName = 10;
entityType = "John";}val p2 : Person2 = {entityName = null;
entityType = null;}