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

Does reapidjson support converting an instance of a struct into json string? #1299

Open
GingerMoon opened this issue Jun 24, 2018 · 3 comments
Labels

Comments

@GingerMoon
Copy link

Does reapidjson support converting an instance of a struct into json string?
And if yes, can the order of the fields be kept in the order of the declaration in the struct?
For example,
struct S {
int Z;
int A;
};
S s = {1,2};

I tried to read the doc but not able to find the answer.
The expect json string is:
{"Z":1, "A":2}

Any sample code would be much appreciated.

@miloyip
Copy link
Collaborator

miloyip commented Jun 24, 2018

No. RapidJSON does not support a framework for automatic serialization/deserialization. Some libraries based on RapidJSON can do so, e.g. Cereal.

However, you may also write code for serialization of your types, e.g.:

void Serialize(Writer<StringBuffer>& writer, const S& s) {
    writer.StartObject();
    writer.Key("Z");
    writer.Int(s.Z);
    writer.Key("A");
    writer.Int(s.A);
    writer.EndObject();
}

void foo() {
    S s = {1, 2};
    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    Serialize(writer, s);
    std::cout << sb.GetString() << std::endl;
}

So that how it is ordered and serialized is completely controlled by youself.

For more information, check http://rapidjson.org/md_doc_sax.html#Writer

@GingerMoon
Copy link
Author

Thanks a lot @miloyip!
I will spend more time on Cereal for the serialization, can I ask you a question, may be stupid, is there any method like writer.Object(...) so that the embedded struct in S can also be printed?
I checked the doc http://rapidjson.org/md_doc_sax.html#Writer but not able to find one.

@miloyip
Copy link
Collaborator

miloyip commented Jun 25, 2018

No. Writer only helps to generate a JSON from those 7 JSON types, not custom defined types.
So you cannot automatically serialize any struct, instead you need to manually write down how to map a struct to JSON.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants