Skip to content

Serializing std::variant<T, std::vector<T>> #2045

Description

@rioki

I am aware of #1261 , but though one special case may be considered. I use a variant to read "scalar" and "vector" of same types. The JSON code would be

{
  "scalar": 42,
  "vector": [1, 2, 3, 4]
}

To map this data into C++ I use a std::variant<double, std::vector> and found the serialization and deserialization to be a bit overly complicated.

After reading up on #1261 I understand why general purpose std::variant can not be serialized and the proposed solution there is not really useful for my use case.

I came up with the following code to integrate this use case into the built in serialization:

namespace nlohmann
{
	template <typename T>
	struct adl_serializer<std::variant<T, std::vector<T>>>
	{
		static void to_json(json& j, std::variant<T, std::vector<T>> const& v)
		{
			std::visit([&](auto&& value) {
				j = std::forward<decltype(value)>(value);
			}, v);
		}

		static void from_json(json const& j, std::variant<T, std::vector<T>>& v)
		{
			if (j.is_array())
			{
				v = j.get<std::vector<T>>();
			}
			else
			{
				v = j.get<T>();
			}
		}
	};
}

Obviously this is not the general / general solution as other containers should be considered and probably it can be done better. It would be nice if this use case can be included in the library, but if not I understand and this request can still be useful for posterity.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions