ppx_deriving_yojson icon indicating copy to clipboard operation
ppx_deriving_yojson copied to clipboard

Allow string (de)serialization

Open seliopou opened this issue 10 years ago • 3 comments

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?

seliopou avatar Oct 05 '15 20:10 seliopou

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.

hcarty avatar Oct 05 '15 21:10 hcarty

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.

seliopou avatar Oct 05 '15 21:10 seliopou

I would accept a PR implementing that.

whitequark avatar Oct 06 '15 05:10 whitequark