我在为JSON序列化时定义选项类型的字段时遇到了问题。
之前有效(无选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string
}
后抛出错误(带选项)
[<DataContract>]
type Article = {
[<field: DataMemberAttribute(Name="version") >]
version: string option
}
方法抛出异常: System.Runtime.Serialization.SerializationException:期望状态'Element'..遇到名为'',namespace''的'Text'。
相关代码
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
答案 0 :(得分:0)
这是一个可以为int
的定义。字符串可以是null,Null引用异常证明了数据......
open System
[<DataContract>]
type Person2 = {
[<DataMember(Name="Name") >]
entityName: Nullable<int>
[<DataMember(Name="Type") >]
entityType: String
}
但是如果你打算用一堆空值来填充它,也许你应该考虑一个类。这真是太可怕了,但它的外观如何:
let p1 = { entityName = Nullable(10); entityType = "John"}
let p2 = { entityName = System.Nullable(); entityType = null}
val p1:Person2 = {entityName = 10;
entityType =&#34; John&#34 ;;}val p2:Person2 = {entityName = null;
entityType = null;}