DataContract / JsonSerializer'@'附加到变量名称

时间:2010-11-17 17:44:07

标签: c# .net json f# datacontract

由于某种原因,我序列化了一个类型(f#):

type JsonKeyValuePair<'T, 'S> =  {
    [<DataMember>] 
    mutable key : 'T
    [<DataMember>] 
    mutable value : 'S
}

let printJson() = 

    use stream = new MemoryStream() 
    use reader = new System.IO.StreamReader(stream)

    let o = {key = "a"; value = 1 }
    let jsonSerializer = Json.DataContractJsonSerializer(typeof<TestGrounds.JsonKeyValuePair<string, int>>)

    jsonSerializer.WriteObject (stream , o)
    stream.Seek(int64 0, SeekOrigin.Begin) |> ignore 

    printfn <| Printf.TextWriterFormat<unit>(reader.ReadToEnd())
    ()

它生成一个字符串:

  

{ “键@”: “一”, “值@”:1}

如果我尝试在没有@符号的情况下反序列化它:

let deserialize() = 
    let json = "{\"key\":\"b\",\"value\":2}"
    let o  = deserializeString<TestGrounds.JsonKeyValuePair<string, int>> json
    ()

{“数据合约类型'TestGrounds.JsonKeyValuePair`2 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[System.Int32,mscorlib,Version = 4.0.0.0 ,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'无法反序列化,因为找不到所需的数据成员'key @,value @'。“}

然而把@回到:

let run2 () = 
    let json = "{\"key@\":\"b\",\"value@\":2}"
    let o  = deserializeString<TestGrounds.JsonKeyValuePair<string, int>> json
    ()

我们都很好。到目前为止我知道在Json Spec中没有引用@(http://www.json.org/)......

1 个答案:

答案 0 :(得分:5)

F#生成名为key@value@的字段,以支持名为keyvalue的属性。尝试在记录类型上添加DataContract属性 - 如果没有它,序列化程序将忽略DataMember属性,并且似乎只写出每个字段。