Deserializing JSON
I'm trying to deserialize a relative simple JSON string, which looks like:
[{
"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
}]
}]
nothing fancy as you see.. except for the Items
array, but that shouldnt really be a problem.
If we then make up a few types that matches the json-string, and a function that will deserialize the string and map it to the types we'll end up with something like:
[<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"
Instead of doing its job, it simply throws following exception, when it's trying to deserialize the string:
Unhandled Exception: System.Runti开发者_Go百科me.Serialization.SerializationException: There was an error deserializing the object of type System.Collections.Generic.IList`1 [[Program+Basic, ConsoleApplication1, Version=0.0.0.0, Culture=neutral, PublicKe yToken=null]]. The data at the root level is invalid. Line 1, position 1.
Am I missing something? - The JSON-string is perfectly valid...
The serializer you are using is for XML you want to use DataContractJsonSerializer.
精彩评论