fsprojects / FSharp.Json

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

Serialize unions without fields as string instead of object with empty array? #27

Closed drhumlen closed 4 years ago

drhumlen commented 5 years ago

type LogLevel = Info | Warn | Error type LogEntry = {Level: LogLevel; Message: string}

shouldn't this be serialized as

{message: "My Message", level: "info"}

instead of

{message: "My Message", level: {"Info": []}} ?

SharpLu.Json does this, but you've went the other way? Is that a conscious decision, or should I make a PR to change it?

Other than that, this library is very promising :)

SharplLu.Json is pretty good too, but the lack of a single-case union serialization support was a dealbreak for me on that one. This library supports that, but lacks the above 🤔

Also, is there a way to use camelCasing instead of PascalCasing in the serialized json? PascalCasing is very unusual in json.

vsapronov commented 5 years ago

Hmmm, I think it's a mistake. I will check more and come back with some solution.

drhumlen commented 5 years ago

It depends on who your consumer is. If it's only for serializing F# to F#, then it's fine as it is. But I would be very surprised to see this type definition real typescript code:

type LogEntry = {
  message: string;
  level: {Info: []} | {Warn: []} | {Error: []};
}

and then

if ('Info' in logEntry.level) {
   return <InfoIcon />
} else if (....

you get the picture. It's very unnatural for an API-consumer.

I realize there's probably some technical edge-cases though.

vsapronov commented 5 years ago

I meant more my mistake that I never considered "enum" style use case for DU. I will fix this but probably in the next major release as it breaks backward compatibility.

dpraimeyuu commented 4 years ago

hi @vsapronov ! Have you had chance to work on that issue? Is there anything I could help with? :-) I also ran into similar issue mentioned in the first comment.

pkese commented 4 years ago

I'm having a similar issue with a list of Enums

type MailFlag = | AirMail | Priority | Confidential | InformDelivery
type Mail = {
   address: string
   flags: MailFlag list
}

and data


{
  "address": "somewhere",
  "flags": ["Priority", "InformDelivery"]
}
vsapronov commented 4 years ago

Sorry, I was distracted by something. Will do my best to make a release with the fix this week.

dpraimeyuu commented 4 years ago

Hi @vsapronov ! Have you had chance to find a solution? 😄

vsapronov commented 4 years ago

Please try version 0.4.0 and let me know if it works for you.

vsapronov commented 4 years ago

Here's documentation: https://github.com/vsapronov/FSharp.Json/blob/master/README.md#union-case-without-fields