1
我试图反序列化相对简单的JSON字符串,它看起来像:反序列化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字符串匹配,将反序列化的字符串,并将其映射到类型,我们会喜欢的东西最后几个类型和函数:
[<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, Version = 0.0.0.0,Culture = neutral, PublicKe yToken = null]]。 的数据根级别无效。第1行, 位置1.
我错过了什么吗? - JSON字符串是完全有效的...
你说得对。我在我的“真实代码”中有这些。不知道我是如何设法让这篇文章错误的。无论如何,即使使用'Basic'数组,它仍然会抛出相同的异常。 (现在更新了数组的帖子) - 谢谢指出:) – ebb
@ebb - 查看更新。 – ChaosPandion
谢谢! - 现在就像一个魅力:) – ebb