我正在尝试反序列化一个相对简单的JSON字符串,如下所示:
[{
"FacebookID": "00000000000000",
"Items": [{
"BillID": "75a9ca7b-3b79-4db0-9867-83b2f66021d2",
"FacebookID": "0000000000",
"Description": "Some description",
"Amount": 5000,
"Accepted": false
}]
}, {
"FacebookID": "00000000000000",
"Items": [{
"BillID": "cec0a6d2-1db9-4a12-ae43-f61c6c69f0a6",
"FacebookID": "0000000000",
"Description": "Some description",
"Amount": 3250,
"Accepted": false
}, {
"BillID": "aaf51bb3-4ae6-48b5-aeb6-9c4d42fd4d2a",
"FacebookID": "0000000000",
"Description": "Some more..",
"Amount": 100,
"Accepted": false
}]
}, {
"FacebookID": "0000000000",
"Items": [{
"BillID": "2124cbc4-2a48-4ba4-a179-31d4191aab6a",
"FacebookID": "0000000000",
"Description": "even more..",
"Amount": 300,
"Accepted": false
}]
}]
你看到的没什么特别的..除了Items
数组,但这不应该是一个问题。
如果我们然后组成一些匹配json-string的类型,以及一个将反序列化字符串并将其映射到类型的函数,我们最终会得到类似的结果:
[<DataContract>]
type Item =
{ [<field: DataMember(Name = "BillID")>]
BillID : string
[<field: DataMember(Name = "FacebookID")>]
FacebookID : string
[<field: DataMember(Name = "Description")>]
Description : string
[<field: DataMember(Name = "Amount")>]
Amount : int
[<field: DataMember(Name = "Accepted")>]
Accepted : bool }
[<DataContract>]
type Basic =
{ [<field: DataMember(Name = "FacebookID")>]
FacebookID : string
[<field: DataMember(Name = "Items")>]
Items : Item array }
// My function to deserialize the json string, and map it to the given type.
let deserializeJson<'a> (s:string) =
use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes s)
let serialize = DataContractSerializer(typeof<'a>)
serialize.ReadObject ms :?> 'a
let get (url:string) =
use web = new WebClient()
web.DownloadString url
// Returns the JSON string
let result = deserializeJson<Basic array> <| get "http://some.com/blabla"
当它试图反序列化字符串时,它只是抛出异常,而不是完成它的工作:
未处理的例外情况: System.Runtime.Serialization.SerializationException: 反序列化时出错 对象类型 System.Collections.Generic.IList`1 [[Program + Basic,ConsoleApplication1, 版本= 0.0.0.0,文化=中立, PublicKe yToken = null]]。数据在 根级别无效。第1行, 位置1。
我错过了什么吗? - JSON字符串完全有效......