'Parsing JSON messages in C++
I am writing an embedded C++ MQTT application which subscribes to topics and receives messages every few seconds.
I need to parse the received String message and get the values into integer variables.
The message format is like this :
{
"date": "2020-12-06T12:31:14.506833+00:00",
"temperature": -9.124567893,
"voltage": 8.444445
}
I would need to save temperature and voltage into different float variables.
What would be the best way to do this? Develop separate code for parsing? Is it worth using some separate libraries to parse it? Thanks.
Solution 1:[1]
So it looks like you need a JSON parser for C or C++. I wrote one for myself and it was not particularly difficult. If you are looking for an existing library, you can find them listed at json.org (https://www.json.org/json-en.html).
Solution 2:[2]
You can use the json-cpp-gen utility for this.
Simply define your message format as a structure:
struct Message {
std::string date;
double temperature;
double voltage;
};
And pass this to json-cpp-gen (see the Readme for specific instructions how). It will automatically generate a JSON parser for this specific structure, which you can then include in your project, and use the parser class to parse each message with a single command.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jon Trauntvein |
Solution 2 | Detheroc |