boostorg / boostorg/json

Investigate simpler, more Nlohmann-like, custom conversions

Open
#1,127 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
479
Forks
110
Avg merge
10d 3h
Merged PRs (30d)
5

Description

For the type
```
struct X
{
std::vector a;
int b;
};
```
our current solution, if we assume lack of physical dependency on Boost.JSON, is
```
namespace boost
{
namespace json
{

class value;

struct value_from_tag;

template
void value_from( T&& t, value& jv );

template
struct value_to_tag;

template
T value_to( value const& jv );

} // namespace json
} // namespace boost

struct X
{
std::vector a;
int b;

template
friend void tag_invoke( boost::json::value_from_tag const&, JV& jv, X const& x )
{
jv = {
{ "a", nullptr },
{ "b", nullptr }
};

boost::json::value_from( x.a, jv.at( "a" ) );
boost::json::value_from( x.b, jv.at( "b" ) );
}

template
friend X tag_invoke( boost::json::value_to_tag const&, JV const& jv )
{
return
{
boost::json::value_to< decltype(X::a) >( jv.at("a") ),
boost::json::value_to< decltype(X::b) >( jv.at("b") )
};
}
};
```
but for nlohmann::json, the above is simply
```
struct X
{
std::vector a;
int b;

template
friend void to_json(Json & j, const X & x)
{
j = {
{"a", x.a},
{"b", x.b}
};
}

template
friend void from_json(const Json & j, X & x)
{
x.a = j.at("a");
x.b = j.at("b");
}
};
```
Note that no forward declarations are needed, because the functionality is fully provided by the JsonValue.

We can achieve something similar if we look for, e.g., `to_boost_json` and `from_boost_json` functions, and make that
```
struct X
{
std::vector a;
int b;

template
friend void to_boost_json(Json & j, const X & x)
{
j = {
{ "a", x.a },
{ "b", x.b }
};
}

template
friend void from_boost_json(const Json & j, X & x)
{
j.at( "a" ).convert_into( x.a );
j.at( "b" ).convert_into( x.b );
}
};
```
or, to avoid requiring default construction of `X`,
```
template
friend X from_boost_json(const Json & j )
{
return
{
j.at( "a" ).convert_to(),
j.at( "b" ).convert_to()
};
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.