Skip to content

Create an example directory and add some code examples. #944

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 17, 2019
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,5 @@ add_subdirectory( src )
#install the includes
add_subdirectory( include )

#install the example
add_subdirectory( example )
29 changes: 29 additions & 0 deletions example/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#vim: et ts =4 sts = 4 sw = 4 tw = 0
cmake_minimum_required(VERSION 3.1)

set(EXAMPLES
readFromString
readFromStream
stringWrite
streamWrite
)
add_definitions(-D_GLIBCXX_USE_CXX11_ABI)
set_property(DIRECTORY PROPERTY COMPILE_OPTIONS ${EXTRA_CXX_FLAGS})

if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra ")
else()
add_definitions(
-D_SCL_SECURE_NO_WARNINGS
-D_CRT_SECURE_NO_WARNINGS
-D_WIN32_WINNT=0x601
-D_WINSOCK_DEPRECATED_NO_WARNINGS)
endif()

foreach (example ${EXAMPLES})
add_executable(${example} ${example}/${example}.cpp)
target_include_directories(${example} PUBLIC ${CMAKE_SOURCE_DIR}/include)
target_link_libraries(${example} jsoncpp_lib)
endforeach()

add_custom_target(examples ALL DEPENDS ${EXAMPLES})
13 changes: 13 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
***NOTE***

If you get linker errors about undefined references to symbols that involve types in the `std::__cxx11` namespace or the tag
`[abi:cxx11]` then it probably indicates that you are trying to link together object files that were compiles with different
values for the _GLIBCXX_USE_CXX11_ABI marco. This commonly happens when linking to a third-party library that was compiled with
an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you need to recompole your code with
the old ABI,just like :
**g++ stringWrite.cpp -ljsoncpp -std=c++11 -D_GLIBCXX_USE_CXX11_ABI=0 -o stringWrite**

Not all of uses of the new ABI will cause changes in symbol names,for example a class with a `std::string` member variable will
have the same mangled bane whether compiled with the older or new ABI. In order to detect such problems the new types and functions
asre annotated with the abi_tag attribute,allowing the compiler to warn about potential ABI incompatibilities in code using them.
Those warnings can be enabled with the `-Wabi-tag` option.
3 changes: 3 additions & 0 deletions example/readFromStream/errorFormat.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
1: "value"
}
32 changes: 32 additions & 0 deletions example/readFromStream/readFromStream.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include "json/json.h"
#include <fstream>
#include <iostream>
/*
parse from stream,collect comments and capture error info.

$g++ readFromStream.cpp -ljsoncpp -std=c++11 -o readFromStream
$./readFromStream
// comment head
{
// comment before
"key" : "value"
}
// comment after
// comment tail
*/
int main(int argc, char* argv[]) {
Json::Value root;
std::ifstream ifs;
ifs.open(argv[1]);
root.clear();

Json::CharReaderBuilder builder;
builder["collectComments"] = true;
JSONCPP_STRING errs;
if (!parseFromStream(builder, ifs, &root, &errs)) {
std::cout << errs << std::endl;
return EXIT_FAILURE;
}
std::cout << root << std::endl;
return EXIT_SUCCESS;
}
6 changes: 6 additions & 0 deletions example/readFromStream/withComment.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// comment head
{
// comment before
"key" : "value"
// comment after
}// comment tail
33 changes: 33 additions & 0 deletions example/readFromString/readFromString.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include "json/json.h"
#include <iostream>
/*
parse a string to Value object with CharReaderBuilder class or Reader class
$g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
$./readFromString
colin
20
*/
int main() {
std::string strRes = R"({"Age": 20, "Name": "colin"})";
auto nLen = (int)strRes.length();
JSONCPP_STRING err;
Json::Value root;

#if 0 // old way
Json::Reader myreader;
myreader.parse(strRes,root);
#else // new way
Json::CharReaderBuilder builder;
std::unique_ptr<Json::CharReader> const reader(builder.newCharReader());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer const foo to foo const

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); ?

if (!reader->parse(strRes.c_str(), strRes.c_str() + nLen, &root, &err)) {
std::cout << "error" << std::endl;
return EXIT_FAILURE;
}
#endif
std::string strName = root["Name"].asString();
int strAge = root["Age"].asInt();

std::cout << strName << std::endl;
std::cout << strAge << std::endl;
return EXIT_SUCCESS;
}
22 changes: 22 additions & 0 deletions example/streamWrite/streamWrite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include "json/json.h"
#include <iostream>
/*
write the Value object to stream
$g++ streamWrite.cpp -ljsoncpp -std=c++11 -o streamWrite
$./streamWrite
{
"Age" : 20,
"Name" : "robin"
}
*/
int main() {
Json::Value root;
Json::StreamWriterBuilder builder;
std::unique_ptr<Json::StreamWriter> const writer(builder.newStreamWriter());

root["Name"] = "robin";
root["Age"] = 20;
writer->write(root, &std::cout);

return EXIT_SUCCESS;
}
33 changes: 33 additions & 0 deletions example/stringWrite/stringWrite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include "json/json.h"
#include <iostream>
/*
write a Value object to a string
$g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
$./stringWrite
{
"action" : "run",
"data" :
{
"number" : 1
}
}
*/
int main() {

Json::Value root;
Json::Value t_data;

root["action"] = "run";
t_data["number"] = 1;
root["data"] = t_data;

#if 0 // old way
Json::FastWriter writer;
std::string json_file = writer.write(root);
#else // new way
Json::StreamWriterBuilder builder;
std::string json_file = Json::writeString(builder, root);
#endif
std::cout << json_file << std::endl;
return EXIT_SUCCESS;
}
2 changes: 1 addition & 1 deletion src/lib_json/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ endif()
# See https://cmake.org/cmake/help/v3.1/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html#prop_gbl:CMAKE_CXX_KNOWN_FEATURES
# for complete list of features available
target_compile_features(jsoncpp_lib PUBLIC
cxx_std_11 # Compiler mode is aware of C++ 11.
# cxx_std_11 # Compiler mode is aware of C++ 11.
#MSVC 1900 cxx_alignas # Alignment control alignas, as defined in N2341.
#MSVC 1900 cxx_alignof # Alignment control alignof, as defined in N2341.
#MSVC 1900 cxx_attributes # Generic attributes, as defined in N2761.
Expand Down
3 changes: 1 addition & 2 deletions src/lib_json/json_value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1436,8 +1436,7 @@ bool Value::isObject() const { return type() == objectValue; }
Value::Comments::Comments(const Comments& that)
: ptr_{cloneUnique(that.ptr_)} {}

Value::Comments::Comments(Comments&& that)
: ptr_{std::move(that.ptr_)} {}
Value::Comments::Comments(Comments&& that) : ptr_{std::move(that.ptr_)} {}

Value::Comments& Value::Comments::operator=(const Comments& that) {
ptr_ = cloneUnique(that.ptr_);
Expand Down
4 changes: 2 additions & 2 deletions src/test_lib_json/jsontest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,8 @@ void Runner::preventDialogOnCrash() {
_CrtSetReportHook(&msvcrtSilentReportHook);
#endif // if defined(_MSC_VER)

// @todo investigate this handler (for buffer overflow)
// _set_security_error_handler
// @todo investigate this handler (for buffer overflow)
// _set_security_error_handler

#if defined(_WIN32)
// Prevents the system from popping a dialog for debugging if the
Expand Down
11 changes: 7 additions & 4 deletions src/test_lib_json/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,17 @@ JSONTEST_FIXTURE(ValueTest, objects) {
JSONTEST_ASSERT_EQUAL(Json::Value(1234), *foundId);

const char unknownIdKey[] = "unknown id";
const Json::Value* foundUnknownId = object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey));
const Json::Value* foundUnknownId =
object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey));
JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId);

// Access through demand()
const char yetAnotherIdKey[] = "yet another id";
const Json::Value* foundYetAnotherId = object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
const Json::Value* foundYetAnotherId =
object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
JSONTEST_ASSERT_EQUAL(nullptr, foundYetAnotherId);
Json::Value* demandedYetAnotherId = object1_.demand(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
Json::Value* demandedYetAnotherId = object1_.demand(
yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
JSONTEST_ASSERT(demandedYetAnotherId != nullptr);
*demandedYetAnotherId = "baz";

Expand Down Expand Up @@ -2495,7 +2498,7 @@ JSONTEST_FIXTURE(IteratorTest, const) {
Json::Value const v;
JSONTEST_ASSERT_THROWS(
Json::Value::iterator it(v.begin()) // Compile, but throw.
);
);

Json::Value value;

Expand Down