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 do i include a vector of pointers in my json? #1997

Closed
Leonetienne opened this issue Mar 18, 2020 · 2 comments
Closed

How do i include a vector of pointers in my json? #1997

Leonetienne opened this issue Mar 18, 2020 · 2 comments

Comments

@Leonetienne
Copy link

I need a result like this:

{
  "result": "success",
  "num_messages": 45,
  "messages":
  [
    {
      "message": "beep boop",
      "timestamp": 39348
    },
    {
      "message": "blib blub",
      "timestamp": 69420
    },
//...
  ]
}

I have the class LogHistory::LogEntry (class inside of another class) and LogHistory provides a static getter for an std::vector<LogEntry*>*

All fine and good for normal iterating, but how do i put this thing into a json?
I tried the to_json(json& j, LogEntry& le) conversion method, but i just get "no suitable conversion method found"

Both of these two get underlined red with "no suitable conversion method found"

json j = LogHistory::GetLogHistory()->at(3);
json j = *LogHistory::GetLogHistory()->at(3);

I think i may have placed the conversion method in the wrong namespace? Right now it's a static member of LogEntry...

Here is my class structure again for clarity...

class LogHistory
{
   public:
      class LogEntry
      {
         public:
            std::string message;
            int timestamp;

            static void to_json(Json& j, const LogEntry& le)
            {
                j = {{"message", le.message}, {"timestamp", le.timestamp}};
            }
      };

      static std::vector<LogEntry*>* GetLogHistory() { return logHistory; }

      private:
         static std::vector<LogEntry*>* logHistory;
};

Would be very happy if someone could point me in the right direction

@Leonetienne
Copy link
Author

It does work when i use a conversion operation, eg

operator json() const
{
   return json{/*...*/};
}

but that obviously does not work with the vector :(

@nlohmann
Copy link
Owner

You must define the to_json method as a free function (no static function) in the same namespace as LogHistory.

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