當(dāng)使用 RapidJSON 的 DOM 方式解析 JSON 時(shí),若解析過(guò)程出現(xiàn)錯(cuò)誤,可以使用 GetParseError_En() 和 GetParseError() 獲取相關(guān)的錯(cuò)誤信息。
需注意的是,關(guān)于解析錯(cuò)誤的處理方式,RapidJSON 的中文文檔和英文文檔給出的示例代碼略有不同。
中文文檔使用了 GetParseErrorCode():
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
// ...
Document d;
if (d.Parse(json).HasParseError()) {
fprintf(stderr, "\nError(offset %u): %s\n",
(unsigned)d.GetErrorOffset(),
GetParseError_En(d.GetParseErrorCode()));
// ...
}
而英文文檔使用的是 GetParseError():
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
// ...
Document d;
if (d.Parse(json).HasParseError()) {
fprintf(stderr, "\nError(offset %u): %s\n",
(unsigned)d.GetErrorOffset(),
GetParseError_En(d.GetParseError()));
// ...
}
經(jīng)試驗(yàn),應(yīng)使用 GetParseError():
error: no member named 'GetParseErrorCode' in 'rapidjson::GenericDocument<rapidjson::UTF8<>>'; did you mean 'GetParseError'?
std::cout << rapidjson::GetParseError_En(document.GetParseErrorCode()) << std::endl;
^~~~~~~~~~~~~~~~~
GetParseError
以下是我的代碼:
#include "rapidjson/document.h"
#include "rapidjson/encodedstream.h"
#include "rapidjson/error/en.h"
#include "rapidjson/istreamwrapper.h"
#include "rapidjson/reader.h"
// ...
std::ifstream inputFileStream("sample.json");
if (!inputFileStream.is_open()) {
// ...
}
rapidjson::IStreamWrapper inputStreamWrapper(inputFileStream); // 用 inputStreamWrapper 包裝 inputFileStream
// AutoUTFInputStream 會(huì)先使用 BOM 來(lái)檢測(cè)編碼。
// 若 BOM 不存在,它便會(huì)使用合法 JSON 的特性來(lái)檢測(cè)。
// 若兩種方法都失敗,它就會(huì)倒退至構(gòu)造函數(shù)提供的 UTF 類型。
rapidjson::AutoUTFInputStream<unsigned, rapidjson::IStreamWrapper> encodedInputStream(inputStreamWrapper); // 用 encodedInputStream 包裝 inputStreamWrapper
rapidjson::Document document; // Document 為 GenericDocument< UTF8<> >
document.ParseStream<0, rapidjson::AutoUTF<unsigned>>(encodedInputStream); // 把任何 UTF 編碼的文件解析至內(nèi)存中的 UTF-8
if (document.HasParseError()) {
std::cout << "------" << std::endl;
std::cout << rapidjson::GetParseError_En(document.GetParseErrorCode()) << std::endl; // 該行會(huì)報(bào)錯(cuò),應(yīng)使用 document.GetParseError()
}
// ...
另外,無(wú)論是中文文檔還是英文文檔,在 rapidjson/document.h 頭文件中,也只有 GetParseError():
template <typename Encoding, typename Allocator = RAPIDJSON_DEFAULT_ALLOCATOR, typename StackAllocator = RAPIDJSON_DEFAULT_STACK_ALLOCATOR >
class GenericDocument : public GenericValue<Encoding, Allocator> {
public:
// ...
//! Get the \ref ParseErrorCode of last parsing.
ParseErrorCode GetParseError() const { return parseResult_.Code(); }
// ...
};
而 GetParseErrorCode() 則出現(xiàn)在 rapidjson/reader.h 頭文件中,也是中英一致,但尚未了解如何使用:
template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator>
class GenericReader {
public:
// ...
//! Get the \ref ParseErrorCode of last parsing.
ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); }
// ...
}; // class GenericReader