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

How to parse a vector of objects with const attributes #1453

Closed
axx opened this issue Jan 23, 2019 · 2 comments
Closed

How to parse a vector of objects with const attributes #1453

axx opened this issue Jan 23, 2019 · 2 comments

Comments

@axx
Copy link

axx commented Jan 23, 2019

Hi,

I have this class:

class MyClass {
  public:
  const std::string _a;
  const std::string _b;
}

I then want to parse [{"a":"aaaaa", "b":"bbbbb"}] to a std::vector<MyClass>.
I tried using the to_json/from_json approach in but I can't because

void from_json(const json& j, MyClass& m) {
  m._a = j.at("a");   // error
 m._b = j.at("b");
}

The other approach using

MyClass from_json(const json& j) {
   return { j.at("a").get<std::string>(), j.at("b").get<std::string>() }
}

also doesn't work because of some requirements in std::vector.

Does someone have other ideas aside from just dropping the const in MyClass?

@theodelrieu
Copy link
Contributor

Hello,

You technically could workaround that by specializing nlohmann::adl_serializer for MyClass.
Although it would not solve the std::vector problem (unless specializing nlohmann::adl_serializer<std::vector<MyClass>>, which is quite brittle especially if you want to support other containers).

I know that everytime I tried to use const member variables, I ended up removing const.
Since it prevents MoveAssignable and CopyAssignable, lots of containers will not work with it.

Removing const and using MyClass const& when needed seems better.

@axx
Copy link
Author

axx commented Jan 24, 2019

Thanks for the ideas!

@axx axx closed this as completed Jan 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants