Skip to content

Document the best way to serialize/deserialize user defined types to json #298

@gnzlbg

Description

@gnzlbg

It would be nice to add an example to the documentation about the best ways to make an user defined type serializable/deserializable to json. For example, given:

struct point {
  float x[3];
};

json v = point{{0., 1., 2.}};
assert(v.is_array());
assert(v[0] == 0.0 and v[1] == 1.0 and v[2] == 2.0);

point p = v; 
assert(p.x[0] == 0.0 and p.x[1] == 1.0 and p.x[2] == 2.0);
  • Is it possible to make json serialization/deserialization without modifying point itself?
  • Are there any customization points to allow this?

For example, to serialize point I think it should probably be enough to:

  • define non-member non-friend begin and end functions that are found by ADL.
  • have this basic_json array constructor use decltype(begin(std::declval<point>())), decltype(end(std::declval<point>())) to find the iterator types, and std::iterator_traits<T> to find the rest of the required types (instead of typename T::value_type) .

Such that adding:

float*       begin(point& p)       { return p.x; }
float const* begin(point const& p) { return p.x; }
float*       end(point& p)       { return p.x + 3; }
float const* end(point const& p) { return p.x + 3; }

to point's namespace should be enough to get it to work. Right now it fails because (for some reason), point is required to have iterator, const_iterator, and value_type type members. But since those can be obtained from point iterators by using std::iterator_traits<decltype(begin(std::declval<point>()))> they are not really necessary.

For other types that are not arrays maybe a couple of customization points could be added (or documented). That way it will be enough to add to_json/from_json overloads to the types namespace to allow them being found by argument dependent lookup.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions