netheril96 / StaticJSON

Fast, direct and static typed parsing of JSON with C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using your library and wondering how do I do this?

shekarmantha opened this issue · comments

Here is a sample code of what I am trying to do:

#include "stdafx.h"
#include <windows.h>
#include

#include "staticjson/document.hpp"
#include "staticjson/staticjson.hpp"
#include "staticjson/io.hpp"

#include "rapidjson/schema.h"

class Base {
private:
int i;
float f;
public:
Base(int i, float f) {
this->i = i;
this->f = f;
}

virtual int staticjson_init(staticjson::ObjectHandler* h) {
	h->add_property("i", &i);
	h->add_property("f", &f);
	return sizeof(*this);
}

};

class Derived : public Base {
private:
double d;
long l;
public:
Derived(double d, long l) : Base(0, 0.0f) {
this->d = d;
this->l = l;
}

virtual int staticjson_init(staticjson::ObjectHandler* h) {
	Base::staticjson_init(h);
	h->add_property("d", &d);
	h->add_property("l", &l);
	return sizeof(*this);
}

};

class Container {
private:
int i;
std::string s;
Base* base;
public:
Container(int i, std::string& s) {
this->i = i;
this->s = s;
}

void setBase(Base* b) {
	this->base = b;
}

virtual void staticjson_init(staticjson::ObjectHandler* h) {
	h->add_property("i", &i);
	h->add_property("s", &s);
	h->Key("Object", strlen("Object"), true);
	h->StartObject();
	h->EndObject(base->staticjson_init(h));
}

};

int main()
{
Container c(55, std::string("a string"));
Derived d(66.35, 1234567890L);
Base b(33, 25.55f);

c.setBase(&d);
std::string s = staticjson::to_json_string(c);
fprintf(stdout, "c serialized value = %s\n", s.c_str());
c.setBase(&b);
s = staticjson::to_json_string(c);
fprintf(stdout, "c serialized value = %s\n", s.c_str());
return 0;

}

This code works and I get the following result:
c serialized value = {"d":66.35,"f":0.0,"i":55,"l":1234567890,"s":"a string"}
c serialized value = {"f":25.549999237060548,"i":55,"s":"a string"}

What I would like to do is get this result:
c serialized value = {"base": {"d":66.35,"l":1234567890}, "f":0.0,"i":55,"s":"a string"}
c serialized value = {"base":{"i":33, "f":"25.55"}, "f":25.549999237060548,"i":55,"s":"a string"}

I don't support raw pointers as they make memory management impossible to handle during parsing. Change the declaration from Base* base to std::unique_ptr<Base> base or std::shared_ptr<Base> base, and h->add_property("base", &base);.