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

Private data on parsing #1802

Closed
TerensTare opened this issue Oct 18, 2019 · 2 comments
Closed

Private data on parsing #1802

TerensTare opened this issue Oct 18, 2019 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@TerensTare
Copy link

  • Describe what you want to achieve.
    I was reading about overloading nllohman::adl_serializer<>.
    Wanted to know how to do that with classes that have protected/private data members.

  • Describe what you tried.

  • Describe which system (OS, compiler) you are using.
    Visual Studio 2019, Windows 10 Home

  • Describe which version of the library you are using (release version, develop branch).
    vcpkg latest release

@nlohmann
Copy link
Owner

This works:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

class Foo
{
  public:
    Foo(int x_, int y_) : x(x_), y(y_) {}

  private:
    int x;
    int y;
  
    // to allow access to private members
    friend void to_json(json& j, const Foo& f);
};

void to_json(json& j, const Foo& f)
{
    j["x"] = f.x;
    j["y"] = f.y;
}

int main() {
    Foo f(1,2);
    
    json j(f);
    std::cout << j << std::endl;
}

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Oct 21, 2019
@TerensTare
Copy link
Author

Thank you for everything.
I wish you happy coding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants