Skip to content

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

Description

@refactormyself

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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    state: needs more infothe author of the issue needs to provide more details

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions