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

Serialize dynamic array #1879

Closed
AlexRos101 opened this issue Dec 24, 2019 · 4 comments
Closed

Serialize dynamic array #1879

AlexRos101 opened this issue Dec 24, 2019 · 4 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@AlexRos101
Copy link

Hi nlohmann!

Thank you for your project.

I have a question.

I want to serialize a dynamic array. The code is like below.

struct person {
		std::string name;
		std::string address;
		int age;
		std::string *emails;	// this is a dynamic array of emails which the person has.
	};

How can I solve this problem?

Thanks.

@frenzisys
Copy link

frenzisys commented Dec 24, 2019 via email

@AlexRos101
Copy link
Author

Hi frenzisys!

Thank you for your reply.

In that case, I can implement from_json function.

Can you send me to_json function in the case of using std::vector?

Thanks.

@nlohmann
Copy link
Owner

std::vector is mapped to an array automatically. You just need to implement to_json/from_json for person. All steps for this are described in https://github.com/nlohmann/json#arbitrary-types-conversions.

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Dec 24, 2019
@dota17
Copy link
Contributor

dota17 commented Jan 17, 2020

Can you send me to_json function in the case of using std::vector?

The example is very simple:

namespace ns {
    struct person {
	std::string name;
	std::string address;
	int age;
	std::vector<std::string> emails;	// this is a dynamic array of emails which the person has.
    };
    void to_json(json& j, const person& p) {
        j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}, {"emails", p.emails}};
    }

    void from_json(const json& j, person& p) {
        j.at("name").get_to(p.name);
        j.at("address").get_to(p.address);
        j.at("age").get_to(p.age);
        j.at("emails").get_to(p.emails);
    }
} // namespace ns

I think this issue could be closed.

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

4 participants