F# Serialization of Record types

后端 未结 4 1104
南旧
南旧 2021-02-04 08:42

I know how to serialize in F# using mutable objects, but is there a way to serialize/deserialize using record types using either XmlSerializer or the DataContractSerializer? loo

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 09:08

    It doesn't use XmlSerializer or the DataContractSerializer, but Json.NET 6.0 includes nice F# support.

    It looks like this:

    type TestTarget = 
        { a: string
          b: int }
    
    []
    type JsonTests() = 
        []
        member x.``can serialize``() = 
            let objectUnderTest = { TestTarget.a = "isa"; b = 9 }
            let jsonResult: string = Newtonsoft.Json.JsonConvert.SerializeObject(objectUnderTest)
            printfn "json is:\n%s" jsonResult
            let xmlResult = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonResult, "root")
            printfn "xml is:\n%s" (xmlResult.OuterXml)
    
            let jsonRoundtrip = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult)
            printfn "json roundtrip: %A" jsonRoundtrip
    
            let xmlAsJson = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlResult, Newtonsoft.Json.Formatting.Indented, true)
            printfn "object -> json -> xml -> json:\n%A" xmlAsJson
            let xmlRoundtrip = Newtonsoft.Json.JsonConvert.DeserializeObject(xmlAsJson)
            printfn "xml roundtrip:\n%A" xmlRoundtrip
    
            Assert.That(true, Is.False)
            ()
    
    json is:
    {"a":"isa","b":9}
    xml is:
    isa9
    json roundtrip: {a = "isa";
     b = 9;}
    object -> json -> xml -> json:
    "{
      "a": "isa",
      "b": "9"
    }"
    xml roundtrip:
    {a = "isa";
     b = 9;}
    

提交回复
热议问题