[英]Parsing JSON With No Tag F#
I am trying to deserialize the following JSON: 我试图反序列化以下JSON:
{
"-L3ELSSzZPRdjCRcFTrb":{
"senderId":"SWs56OIGzMdiCjSXahzDQX8zve92",
"senderName":"alberto",
"text":"Hi"
},
"-L3EN1NW5hHWBTEGC9ve":{
"senderId":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
"senderName":"David",
"text":"Hey"
}
}
To do so I have created the following two records: 为此,我创建了以下两条记录:
type MessageContent =
{ senderId: string
senderName: string
text: string; }
type Messages =
{
messages_list : Map<string,MessageContent>;
}
Next, I call: 接下来,我打电话给:
let messages_json = JsonConvert.DeserializeObject<Types.Messages>(html)
however, this produces the following result: 但是,这会产生以下结果:
{{messages_list = null;}}
The problem seems to be that there is no messages_list
tag in the JSON, so the converter cannot find this tag and returns null. 问题似乎是JSON中没有messages_list
标记,因此转换器无法找到此标记并返回null。 How would I handle a jSON like this though where no initial tag is available? 虽然没有可用的初始标签,但我如何处理这样的jSON?
The easiest way of doing this is probably by using the [<JsonExtensionData>]
attribute and adding [<CLIMutable>]
最简单的方法是使用[<JsonExtensionData>]
属性并添加[<CLIMutable>]
Change your Messages type like this (you might also have to add [<CLIMutable>]
to your MessageContent
type) 像这样更改您的消息类型(您可能还需要将[<CLIMutable>]
添加到MessageContent
类型)
[<CLIMutable>]
type Messages = { [<JsonExtensionData>] messages : IDictionary<string, JToken> }
Then you can deserialize it into a map like this 然后你可以将它反序列化为这样的地图
let msg = JsonConvert.DeserializeObject<Messages>(html)
let messagemap =
msg.messages
|> Seq.map (fun kvp -> kvp.Key, kvp.Value.ToObject<MessageContent>())
|> Map.ofSeq
which will leave you with a map of MessageContent
records. 这将为您留下MessageContent
记录的地图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.