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