5

If I defined a record that implements an interface with an additional property the interface properties are not serialized by json.net. How do I get json.net to serialize those interface properties. Here is an example

open Newtonsoft.Json

type IRecord =
    abstract member id : string

type ARec = {
    Name : string
} with
    interface IRecord with
        member this.id = this.Name

let aRec = {Name = "John"}

Both JsonConvert.SerializeObject aRec and JsonConvert.SerializeObject (aRec :> IRecord) result in {"Name":"John"} but I expected {"Name":"John"; "id":"John"}

I tried adding ShouldSerializeid to the interface but that made no difference.

jbeeko
  • 457
  • 3
  • 10
  • 1
    Well all interfaces are explicitly implemented in f# so it would seem like the solution to [Is it possible to json-serialize a class with explicitly implemented interface properties?](https://stackoverflow.com/q/45608948), which is to apply `[JsonProperty]`, should work here also... but it does not, see https://dotnetfiddle.net/jrXdqh. As best I can tell f# seems to implement them as *methods* rather than *properties*. Compare with a c# port of the fiddle above here: https://dotnetfiddle.net/xGImSQ and you will see that the f# type `ARec` has only one property while the c# type has two. – dbc Oct 13 '18 at 20:56

0 Answers0