Es gibt zwei Methoden, um in boost::json zu überprüfen, ob ein Wert existiert und einen bestimmten Typ hat. Unten findest du ein vollständiges Beispiel, in dem du beide Methoden testen kannst. Ich empfehle generell Option 1, da es mühsam ist, alle Überprüfungen zu 100% korrekt durchzuführen und man oft einige Randfälle vergisst.
Nur für Embedded-Systeme, bei denen Exceptions deaktiviert sind (und deren Aktivierung keine Option ist), ist Option 2 der richtige Weg.
Option 1: Exceptions abfangen
check_value.cpp
void extractTimestamp(const boost::json::value& jv) {
try {
double timestamp = jv.as_object().at("timestamp").as_double();
std::cout << "Timestamp: " << timestamp << std::endl;
} catch (const boost::system::system_error& e) {
std::cerr << "Error" << e.code() << ": " << e.what() << std::endl;
}
}Option 2: Explizite Überprüfungen verwenden
check_value_explicit.cpp
void extractTimestamp2(const boost::json::value& jv) {
// Extrahiere den Timestamp als double
if (jv.is_object() && jv.as_object().contains("timestamp")) {
double timestamp = jv.as_object().at("timestamp").as_double();
std::cout << "Timestamp: " << timestamp << std::endl;
} else {
std::cerr << "Error: 'timestamp' field is missing in the JSON data." << std::endl;
}
}Vollständiger Testfall
check_value_test.cpp
#include <boost/json.hpp>
#include <iostream>
// TODO: Füge hier eine der extractTimestamp-Funktionen ein!
int main() {
// Test mit korrektem JSON
{
std::string line = "{\"timestamp\":1675910171.91}";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
// Test mit inkorrektem JSON #1
{
std::string line = "{}";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
// Test mit inkorrektem JSON #2
{
std::string line = "[]";
boost::json::value jv = boost::json::parse(line);
extractTimestamp(jv);
}
return 0;
}Ausgabe für Option 1:
output_option1.txt
Timestamp: 1.67591e+09
Error boost.json:17: out of range [boost.json:17 at /usr/include/boost/json/impl/object.hpp:388 in function 'at']
Error boost.json:31: value is not an object [boost.json:31 at /usr/include/boost/json/value.hpp:2529 in function 'as_object']Ausgabe für Option 2:
Beachte, dass die Fehlermeldung hier nicht sehr spezifisch ist.
output_option2.txt
Timestamp: 1.67591e+09
Error: 'timestamp' field is missing in the JSON data.
Error: 'timestamp' field is missing in the JSON data.Wenn dieser Beitrag dir geholfen hat, erwäge, mir einen Kaffee zu spendieren oder per PayPal zu spenden, um die Recherche und Veröffentlichung neuer Beiträge auf TechOverflow zu unterstützen