ebb
ebb

Reputation: 9377

Deserialize option<'a>

When trying to deserialize a record member of type Header option returned from a JSON string, I get the following exception:

The data contract type 'Microsoft.FSharp.Core.FSharpOption`1[[MyWeb.Controllers.Header, MyWeb.Controllers, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]' cannot be deserialized because the required data member 'value' was not found.

I'm serializing/deserializing a Message record:

[<DataContract>]
type Header = 
    { [<DataMember>] mutable ID          : int
      [<DataMember>] mutable Description : string }

[<DataContract>]
type Message =
    { [<DataMember>] mutable ID          : int
      [<DataMember>] mutable Header      : Header option
      [<DataMember>] mutable SenderID    : string
      [<DataMember>] mutable ReceiverID  : string }

The code I use to deserialize the JSON:

let deserializeJson<'a> (s:string) =   
    use ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes s)   
    let serialize = DataContractJsonSerializer(typeof<'a>)   
    serialize.ReadObject ms :?> 'a 

And the actual raw JSON result:

"Message":
{
    "ID":13,
    "Header": { "Value":{"ID":21,"Description":"some"}},
    "SenderID":"312345332423",
    "ReceiverID":"16564543423" 
}

The question: how do I deserialize a 'a option?

Update

ASP.NET MVC uses JavaScriptSerializer by default to serialize objects and I'm using DataContractJsonSerializer to deserialize.

For some reason it seems DataContractJsonSerializer can't read the JSON string unless the Value property for the option is in lowercase (as pointed out by @svick). A dirty fix would be to replace "Value" with "value" in the returned JSON string, but I've chosen to go with Roberts' suggestion.

Upvotes: 2

Views: 662

Answers (1)

Robert
Robert

Reputation: 6437

If you were to hop over to using json.net (a.k.a Newtonsoft.Json) instead of the json serializer that comes with the .NET framework, then you could use the option serializer I built to allow me to work more effectively with ravendb. Should just be a matter of registering the convert with the serializer and calling Deserialize.

Upvotes: 1

Related Questions