fsprojects / FSharp.Json

F# JSON Reflection based serialization library
Apache License 2.0
222 stars 26 forks source link

Support expanding the content of an object to the upper layer #56

Open shanoaice opened 2 years ago

shanoaice commented 2 years ago

For example, I wanted to serialize the following records:

type Ex1 = { Val1: int }
type Ex2 = { Nested: Ex1; Val2: int }
let data = { Nested = { Val1 = 1 }; Val2 = 2 }
let json = Json.serialize data

into such form:

{
    "val1": 1,
    "val2": 2
}

It seemed like that this is impossible to achieve with FSharp.Json for now.
Is it possible to have a [<Expand>] attribute to achieve such task?

I got this idea because I wanted to expand the result of serializing a DU with union case key / value mode, like so:

[<JsonUnion(Mode = UnionMode.CaseKeyAsFieldValue, CaseKeyField="casekey", CaseValueField="casevalue")>]
type DU = | Example of string
type ExRec = { Val: int; Union: DU }
let data = { Val = 1; Union = DU.Example "str" }
let json = Json.serialize data

into such form:

{
    "val": 1,
    "casekey": "Example",
    "casevalue": "str"
}