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

deserializing arrays should be part of the library #2575

Closed
user1095108 opened this issue Jan 8, 2021 · 4 comments
Closed

deserializing arrays should be part of the library #2575

user1095108 opened this issue Jan 8, 2021 · 4 comments

Comments

@user1095108
Copy link

user1095108 commented Jan 8, 2021

This code should not be necessary:

template <typename T, std::size_t N>
struct adl_serializer<std::array<T, N>>
{
  static auto from_json(json const& j)
  {
    if (j.is_array() && (N == j.size()))
    {
      std::array<T, N> r;

      std::copy(std::cbegin(j), std::cend(j), std::begin(r));

      return r;
    }
    else
    {
      return std::array<T, N>{};
    }
  }

  static void to_json(json& j, std::array<T, N> const& a)
  {
    std::copy(std::cbegin(a), std::cend(a),
      std::back_inserter(j = json::array()));
  }
};

I consider this an oversight that needs to be fixed. The same applies to standard arrays (i.e. T[N]).

@nlohmann
Copy link
Owner

nlohmann commented Jan 8, 2021

I may misunderstand the issue, but this works without the serializer you propose:

json j = {1,2,3};
std::array<int, 3> a = j;
json k = a;

@user1095108
Copy link
Author

user1095108 commented Jan 8, 2021

The issue was my idiom:
auto const a(j.get<std::array<int, 3>());
So, I'll close this issue, but it's a good idea, you're aware of the idiom :) I'm lazy and like using auto wherever I can, some people consider this a good practice.

BTW: There is a difference. My serializer doesn't throw, while your conversion might.

@nlohmann
Copy link
Owner

nlohmann commented Jan 8, 2021

Hmm...

json j = {1,2,3};
auto const a(j.get<std::array<int, 3>>());
json k = a;

also works out of the box. Am I overlooking anything?

@user1095108
Copy link
Author

Could be I had an outdated version of your library. Just this morning I was getting errors, but didn't save them :(

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

2 participants