I'm using RapidJSON to parse an incoming JSON file, I can iterate and get the value through the different nests. I mean the variable values (i.e.: protocolVersion = 2). But I cannot get the start of a nest { : }. Using the following JSON as an example:
{
"header":{
"protocolVersion":2,
"messageID":2,
"stationID":224,
"data":
{
1:
2:
3:
}
},
}
I want to parse "header" and "data". I'm using this line but it doesn't match as a parse way
ItsPduHeader_t& header = message->header;
And trying this, I get an error:
ItsPduHeader_t& header = doc["header"].GetObject();
error: invalid initialization of non-const reference of type ‘ItsPduHeader_t&’ {aka ‘ItsPduHeader&’} from an rvalue of type ‘rapidjson::GenericValue<rapidjson::UTF8<> >::Object’ {aka ‘rapidjson::GenericObject<false, rapidjson::GenericValue<rapidjson::UTF8<> > >’}
381 | ItsPduHeader_t& header = doc["header"].GetObject();
How can I do it?
There are 2 overloaded methods in source code of RapidJSON:
Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); }
ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); }
And all of them return object by value. You should try to define header
like simple object (not reference) or const reference to object.
Update
Your json is not correct at first. You can't get ItsPduHeader_t
from RapidJSON simple types directly. You should get RapidJSON object representation for header
and then for data
and query it:
const char* json = "{\"header\":{\"protocolVersion\" : 2,\"messageID\":2,\"stationID\":224,\"data\":{\"foo\":\"bar\"}}}";
rapidjson::Document d;
d.Parse(json);
for (const auto& m : d["header"]["data"].GetObject()) {
std::cout << m.name.GetString() << " " << m.value.GetType() << std::endl;
}
const auto& header = d["header"];
const auto& data = header["data"];
std::cout << "header->data->foo: " << data["foo"].GetString();