Alk
Alk

Reputation: 5557

Parsing JSON With No Tag F#

I am trying to deserialize the following 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. How would I handle a jSON like this though where no initial tag is available?

Upvotes: 1

Views: 56

Answers (1)

wasatz
wasatz

Reputation: 4278

The easiest way of doing this is probably by using the [<JsonExtensionData>] attribute and adding [<CLIMutable>]

Change your Messages type like this (you might also have to add [<CLIMutable>] to your MessageContent type)

[<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.

Upvotes: 3

Related Questions