C++ 解析JSON 用什么库好呢?

JSON官网看看有没有什么库推荐的

一眼瞅上去这个 JSON for modern C++ 看上去挺顺眼的

好,就它了!

点击去就是这个项目的GitHub

先去下载最新的  Release

把这个include 解压到你的编译器include目录下面

我这台Windows 上安装了 MinGW64

所以我将它解压到了这里

至此JSON解析库已经安装好了

那么该如何使用呢?

还是看看作者写的文档吧

https://github.com/nlohmann/json/tree/develop/doc/examples

这个作者真是给力,example 写了好多啊(德国大佬真能写)(滑稽)

随便挑一个例子试一试吧

 

test.cpp

#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create a JSON object
    json j =
    {
        {"pi", 3.141},
        {"happy", true},
        {"name", "Niels"},
        {"nothing", nullptr},
        {
            "answer", {
                {"everything", 42}
            }
        },
        {"list", {1, 0, 2}},
        {
            "object", {
                {"currency", "USD"},
                {"value", 42.99}
            }
        }
    };

    // add new values
    j["new"]["key"]["value"] = {"another", "list"};

    // count elements
    auto s = j.size();
    j["size"] = s;

    // pretty print with indent of 4 spaces
    std::cout << std::setw(4) << j << '\n';
}

 

 

test2.cpp

#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create a JSON object
    json j =
    {
        {"pi", 3.141},
        {"happy", true},
        {"name", "Niels"},
        {"nothing", nullptr},
        {
            "answer", {
                {"everything", 42}
            }
        },
        {"list", {1, 0, 2}},
        {
            "object", {
                {"currency", "USD"},
                {"value", 42.99}
            }
        }
    };

    // add new values
    j["new"]["key"]["value"] = {"another", "list"};

    // count elements
    auto s = j.size();
    j["size"] = s;

    // pretty print with indent of 4 spaces
    std::cout << j["happy"] << '\n';
}

还行,,,,慢着有点不对劲啊

这生成的可执行程序体积有点大啊!

 

 

 

简单应用的话无外乎就是

读取字符串里面的JSON然后生成JSON对象

取任意的 名称/值 

JSON对象转化为字符串形式导出

其中导入/导出最为关键

 

从 char[]  String  或者 file中读取文本返回JSON “对象”


static basic_json nlohmann::basic_json::parse	(	detail::input_adapter && 	i,
                                                        const parser_callback_t 	cb = nullptr,
                                                        const bool 	allow_exceptions = true 
)	

Parameters

[in] i input to read from
[in] cb a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional)
[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default)

 

从字符数组中读取

 #include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
 
 using json = nlohmann::json;
 
 int main()
 {
     // a JSON text
     char text[] = R"(
     {
         "Image": {
             "Width":  800,
             "Height": 600,
             "Title":  "View from 15th Floor",
             "Thumbnail": {
                 "Url":    "http://www.example.com/image/481989943",
                 "Height": 125,
                 "Width":  100
             },
             "Animated" : false,
             "IDs": [116, 943, 234, 38793]
         }
     }
     )";
 
     // parse and serialize JSON
     json j_complete = json::parse(text);
     std::cout << std::setw(4) << j_complete << "\n\n";
}

 

从String 对象中读取

 #include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
 #include <string>
 using json = nlohmann::json;
 
 int main()
 {
     // a JSON text
     std::string text = R"(
     {
         "Image": {
             "Width":  800,
             "Height": 600,
             "Title":  "View from 15th Floor",
             "Thumbnail": {
                 "Url":    "http://www.example.com/image/481989943",
                 "Height": 125,
                 "Width":  100
             },
             "Animated" : false,
             "IDs": [116, 943, 234, 38793]
         }
     }
     )";
 
     // parse and serialize JSON
     json j_complete = json::parse(text);
     std::cout << std::setw(4) << j_complete << "\n\n";
     std::cout << std::setw(4) << j_complete["Image"]["IDs"] << "\n";
}

 

将JSON对象导出为字符串


string_t nlohmann::basic_json::dump	(	const int 	indent = -1,
                                                const char 	indent_char = ' ',
                                                const bool 	ensure_ascii = false,
                                                const error_handler_t 	error_handler = error_handler_t::strict 
}

Parameters

[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1(the default) selects the most compact representation.
[in] indent_char The character to use for indentation if indent is greater than 0. The default is (space).
[in] ensure_ascii If ensure_ascii is true, all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result consists of ASCII characters only.
[in] error_handler how to react on decoding errors; there are three possible values: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization).
#include <iostream>
 #include <nlohmann/json.hpp>
 
 using json = nlohmann::json;
 
 int main()
 {
     // create JSON values
     json j_object = {{"one", 1}, {"two", 2}};
     json j_array = {1, 2, 4, 8, 16};
     json j_string = "Hellö 😀!";
 
     // call dump()
     std::cout << "objects:" << '\n'
               << j_object.dump() << "\n\n"
               << j_object.dump(-1) << "\n\n"
               << j_object.dump(0) << "\n\n"
               << j_object.dump(4) << "\n\n"
               << j_object.dump(1, '\t') << "\n\n";
 
     std::cout << "arrays:" << '\n'
               << j_array.dump() << "\n\n"
               << j_array.dump(-1) << "\n\n"
               << j_array.dump(0) << "\n\n"
               << j_array.dump(4) << "\n\n"
               << j_array.dump(1, '\t') << "\n\n";
 
     std::cout << "strings:" << '\n'
               << j_string.dump() << '\n'
               << j_string.dump(-1, ' ', true) << '\n';
 
     // create JSON value with invalid UTF-8 byte sequence
     json j_invalid = "ä\xA9ü";
     try
     {
         std::cout << j_invalid.dump() << std::endl;
     }
     catch (json::type_error& e)
     {
         std::cout << e.what() << std::endl;
     }
 
     std::cout << "string with replaced invalid characters: "
               << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
               << "\nstring with ignored invalid characters: "
               << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
               << '\n';
 }

 

 

具体参考:https://nlohmann.github.io/json/index.html