boost::json: Bir değerin var olup olmadığını ve belirli bir tipte olup olmadığını kontrol etme

boost::json‘de bir değerin var olup olmadığını ve belirli bir tipte olup olmadığını kontrol etmenin iki yöntemi vardır. Her iki yöntemi de test edebileceğiniz tam bir örnek için aşağıya bakın. Genel olarak Seçenek 1‘i öneririm çünkü tüm kontrolleri %100 doğru yapmak zahmetlidir ve genellikle bazı uç durumlar unutulur.

Yalnızca istisnaların devre dışı olduğu gömülü sistemlerde (ve etkinleştirmenin bir seçenek olmadığı durumlarda) Seçenek 2 kullanılmalıdır.

Seçenek 1: İstisnaları yakalama

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;
    }
}

Seçenek 2: Açık kontroller kullanma

check_value_explicit.cpp
void extractTimestamp2(const boost::json::value& jv) {
    // Zaman damgasını double olarak çıkar
    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;
    }
}

Tam test durumu

check_value_test.cpp
#include <boost/json.hpp>
#include <iostream>

// TODO: Buraya extractTimestamp fonksiyonlarından birini ekleyin!

int main() {
    // Doğru JSON ile test
    {
        std::string line = "{\"timestamp\":1675910171.91}";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }

    // Hatalı JSON #1 ile test
    {
        std::string line = "{}";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }

    // Hatalı JSON #2 ile test
    {
        std::string line = "[]";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }

    return 0;
}

Seçenek 1 çıktısı:

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']

Seçenek 2 çıktısı:

Buradaki hata mesajının çok spesifik olmadığını unutmayın.

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.

Check out similar posts by category: Boost C/C++