From 98959e28207c154713e7691c35245460c4c87bfb Mon Sep 17 00:00:00 2001 From: "Philipp A. Hartmann" Date: Thu, 26 Nov 2015 22:30:59 +0100 Subject: [PATCH 1/2] GenericDocument: add implicit conversion to ParseResult To simplify the error handling, this commit adds an implicit conversion of GenericDocument to ParseResult, allowing code like (already in the documentation): ParseResult ok = doc.Parse(json); if (!ok) // ... --- include/rapidjson/document.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/include/rapidjson/document.h b/include/rapidjson/document.h index 1ee4fb6..b708a5a 100644 --- a/include/rapidjson/document.h +++ b/include/rapidjson/document.h @@ -1986,6 +1986,17 @@ public: //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } + //! Implicit conversion to get the last parse result + /*! \return \ref ParseResult of the last parse operation + + \code + Document doc; + ParseResult ok = doc.Parse(json); + if (!ok) + printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset()); + \endcode + */ + operator ParseResult() const { return parseResult_; } //!@} //! Get the allocator of this document. From 9378001e355a1f470a5ff8a49a9834545d17c541 Mon Sep 17 00:00:00 2001 From: "Philipp A. Hartmann" Date: Thu, 26 Nov 2015 22:33:14 +0100 Subject: [PATCH 2/2] documenttest.cpp: check/use conversion from Document to ParseResult --- test/unittest/documenttest.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/unittest/documenttest.cpp b/test/unittest/documenttest.cpp index 0d84194..e4d1432 100644 --- a/test/unittest/documenttest.cpp +++ b/test/unittest/documenttest.cpp @@ -28,6 +28,7 @@ void ParseCheck(DocumentType& doc) { typedef typename DocumentType::ValueType ValueType; EXPECT_FALSE(doc.HasParseError()); + EXPECT_TRUE((ParseResult)doc); EXPECT_TRUE(doc.IsObject()); @@ -99,13 +100,18 @@ TEST(Document, UnchangedOnParseError) { Document doc; doc.SetArray().PushBack(0, doc.GetAllocator()); - doc.Parse("{]"); + ParseResult err = doc.Parse("{]"); EXPECT_TRUE(doc.HasParseError()); + EXPECT_EQ(err.Code(), doc.GetParseError()); + EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsArray()); EXPECT_EQ(doc.Size(), 1u); - doc.Parse("{}"); + err = doc.Parse("{}"); EXPECT_FALSE(doc.HasParseError()); + EXPECT_FALSE(err.IsError()); + EXPECT_EQ(err.Code(), doc.GetParseError()); + EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsObject()); EXPECT_EQ(doc.MemberCount(), 0u); }