Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow string (de)serialization #37

Open
seliopou opened this issue Oct 5, 2015 · 3 comments
Open

Allow string (de)serialization #37

seliopou opened this issue Oct 5, 2015 · 3 comments

Comments

@seliopou
Copy link

seliopou commented Oct 5, 2015

Supporting string (de)serialization for types that do not support yojson functions may help library authors make use of ppx_deriving_yojson. This could use the existing convention of labeling a type with [@encoding string] to do string serialization instead of yojson serialization for large numbers. For example consider the (pseudo) code below:

module A : sig
  (* This module comes from package a *)
  type t
  val to_string : t -> string
  val of_string : string -> t
end

module B : sig
  (* This module comes from package b *)
  type t [@@deriving yojson]
end

module C : sig
  (* Somebody's trying to write this module in package c, with a and b as dependencies *)
  type t =
    | A of (A.t [@encoding `string])
    | B of B.t
    [@@deriving yojson]
end

The effect here would be that C.to_yojson would encode a B variant normally, but would encode an A variant with the leading "A" tag as usual, while using A.to_string to encode the value that variant contains.

I was looking into implementing this but thought to solicit feedback before proceeding much more. Thoughts?

@hcarty
Copy link
Contributor

hcarty commented Oct 5, 2015

This would be quite useful. int and float versions as well. I've used each of these in manual form when working with external libraries.

@seliopou
Copy link
Author

seliopou commented Oct 5, 2015

To add to my original comment (which I made a few edits to for readability), the most recent time I came across this was while I was using the ipaddr library. Specifically I wanted to serialize an Ipaddr.V4.Prefix.t. Under the hood this is an int32 * int, but for serialization purposes the x.x.x.x/x would satisfactory, if not preferable.

Of course doing the type aliasing and writing the (de)serializers manually would be very simple, but this use-case may warrant special support from the library.

@whitequark
Copy link
Collaborator

I would accept a PR implementing that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants