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

Serializing/Deserializing a Class containing a vector of itself #1373

Closed
refactormyself opened this issue Nov 24, 2018 · 2 comments
Closed
Labels
state: needs more info the author of the issue needs to provide more details

Comments

@refactormyself
Copy link

I have a class structure similar to the one below. I want to serialize and deserialize object. Please can you help me with the "from_json" method

namespace ns {
	// a simple struct to model a person
	struct person {
		std::string name;
		std::string address;
		int age;
		std::vector<person> children{};

		void to_json(json& j, const person& p) {
			// j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
			json child_json;
			for (auto child : p.children)
			{
				json i;
				to_json(i, child);
				child_json.push_back(i);
			}
			j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age}, {"children", child_json} };
		}

		static 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("children").get_to<std::vector<person>>(p.children); //DOES NOT COMPILE
		}
	};

int main(array<System::String ^> ^args)
{
	ns::person p1{ "Ned Flanders", "744 Terrace", 60 };
	ns::person p2{ "Ned Flanders", "7 Everrace", 90 };
	ns::person p3{ "Ned Flanders", "4 Evergreen" , 6 };
	ns::person p{ "The Father", "Evergreen", 160, {p1, p2, p3} };
	json js;

	p.to_json(js, p);
	
	std::cout << js.dump(3) << std::endl;
    return 0;
}
@refactormyself refactormyself changed the title Serializing/Deserializing Container Class Serializing/Deserializing a Class containing a vector of itself Nov 25, 2018
@gregmarr
Copy link
Contributor

to_json and from_json should be in namespace ns, not members of the struct.

@nlohmann
Copy link
Owner

@refactormyself Does the hint from @gregmarr fixes the issue?

@nlohmann nlohmann added the state: needs more info the author of the issue needs to provide more details label Dec 12, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
state: needs more info the author of the issue needs to provide more details
Projects
None yet
Development

No branches or pull requests

3 participants