C++ json支持

<json>

{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}"; 
{
    "uploadid": "UP000000",
    "code": 100,
    "msg": "none",
    "files": "none"

json配置过程

看了网上的博客和一些文章整了半天整不出来,vs也各种报错,真是气人。
好像又回到了过去一天到晚百度就是为了解决vs各种环境记语法问题。

后来再反复找源代码,并仔细对比各个博客异同之处,并在vs上一步步操作,总算完成一部输出

    *首先下载源文件解压 https://github.com/open-source-parsers/jsoncpp/releases
    *将include\json和src\lib_json目录里的文件手动添加到VS工程中(在vs中工程目录下新建filter文件夹,然后将之前提到的这些文件全都add 进来)
    *将filter文件夹中的json_reader.cpp、json_value.cpp和json_writer.cpp三个文件右键属性,Precompiled Header属性设置为Not Using Precompiled Headers,否则编译会出现错误。
    *在VS工程的属性C/C++下General中Additional Include Directories包含头文件目录\include。在使用的cpp文件中包含json头文件即可,代码头部加入#include "json/json.h"。

参考文章 
https://www.cnblogs.com/liaocheng/p/4243731.html
https://www.cnblogs.com/yelongsan/p/4134384.html
https://blog.csdn.net/xt_xiaotian/article/details/5648388

{\"Id\" :1, \"Name\" : \"cctrys\" , \"Age\" :23,\"Address\" :[{ \"City\" : \"Beijing\" , \"ZipCode\" : \"111111\" }, { \"City\" : \"Shanghai\" , \"ZipCode\" : \"222222\" }], \"Email\" : \"[email protected]\"}";
{
    "Id" : 1,
    "Name" : "cctrys" ,
    "Age" :23,
    "Address" : 
    [
        { "City" : "Beijing" ,     "ZipCode" : "111111" }, 
        { "City" : "Shanghai" , "ZipCode" : "222222" }
    ], 
    "Email" : "[email protected]"
}

#include "json/json.h"
Json::Reader read;
Json::Value jsonObj;
在主函数中加入语句,运行正常
string strValue2 = "{\"Id\" :1, \"Name\" : \"cctrys\" , \"Age\" :23,\"Address\" :[{ \"City\" : \"Beijing\" , \"ZipCode\" : \"111111\" }, { \"City\" : \"Shanghai\" , \"ZipCode\" : \"222222\" }], \"Email\" : \"[email protected]\"}";
if (read.parse(strValue2, jsonObj)) {
    std::string name = jsonObj["Name"].asCString();
    std::cout << name << std::endl;
}
输出cctrys
//------------------------------------
访问子节点
if (!jsonObj["Address"].isNull())
{
    int file_size = jsonObj["Address"].size();
    std::cout << "address size" << file_size  << std::endl;
    // 遍历数组

    Json::Value val_address;
    if (file_size >= 1)
        val_address = jsonObj["Address"];


    for (int i = 0; i < file_size; ++i)
    {
        std::string citys = val_address[i]["City"].asString();
        std::cout  << " city " << citys << std::endl;
    }
}
输出 
address size 2
city Beijing
city Shanghai
//------------------------------------
迭代器获取json的key
Json::Value myjson = jsonObj["Address"][0];//getJsonFromFile(“test.json”);
Json::Value::Members members(myjson.getMemberNames());

for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
    const std::string &key = *it;
    std::cout << key << std::endl;
}
输出 
City
ZipCode

//--------------------------
{
   "a" : [
      {
         "date" : "2011-11-11",
         "date2" : "2011-11-12",
         "date3" : "2011-11-13"
      },
      {
         "time" : "11:11:11"
      }
   ],
   "code" : 100,
   "date" : "2011-11-11",
   "datex" : 666,
   "datexx" : {
      "date" : "2011-11-11",
      "date2" : "2011-11-12",
      "date3" : "2011-11-13"
   },
   "files" : "",
   "msg" : "",
   "uploadid" : "UP000000"
}
这其中那个“[]”是否有特殊意义?
//源自 https://www.cnblogs.com/gimin/p/5295952.html
在JavaScript中,通常用[]创建的数据格式称为数组,用{}创建的东西称为对象。
有一个数组a=[1,2,3,4],还有一个对象a={0:1,1:2,2:3,3:4},运行alert(a[1]),两种情况下的运行结果是相同的!这就是说,数据集合既可以用数组表示,也可以用对象表示,那么到底该用哪一种呢? 
其实数组表示有序数据的集合,而对象表示无序数据的集合。如果数据的顺序很重要,就用数组,否则就用对象。 
当然,数组和对象的另一个区别是,数组中的数据没有“名称”(name),对象中的数据有“名称”(name)。但是问题是,很多编程语言中,都有一种叫 做“关联数组“(associativearray)的东西。这种数组中的数据是有名称的。

//========================================示例测试代码

#include "json/json.h"
Json::Reader read;
Json::Value jsonObj;

using std::string;
using std::vector;
//初始化
std::map<std::string, size_t> people{ {"Ann", 25}, {"Bill", 46},{"Jack", 32},{"Jill", 32} };

class Name
{
public:
    Name(const std::string& name1, const std::string& name2) : first(name1), second(name2) {}
    //~Name();

private:
    std::string first{};
    std::string second{};
};

int main()
{
    //    std::cout << "Hello World!\n"; 
    string strValue = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
    string strValue2 = "{\"Id\" :1, \"Name\" : \"cctrys\" , \"Age\" :23,\"Address\" :[{ \"City\" : \"Beijing\" , \"ZipCode\" : \"111111\" }, { \"City\" : \"Shanghai\" , \"ZipCode\" : \"222222\" }], \"Email\" : \"[email protected]\"}";
    Json::Value root;
    if (read.parse(strValue, root)) {
        std::string out = root.toStyledString();
        std::cout << out << std::endl;
//        root.append("xx:xx");    
        Json::Value arrayObj=root;   // 构建对象  
        Json::Value new_item, new_item1;
        new_item["date"] = "2011-11-11";
        new_item["date2"] = "2011-11-12";
        new_item["date3"] = "2011-11-13";
        new_item1["time"] = "11:11:11";
        arrayObj["date"] = "2011-11-11";
        arrayObj["datex"] = Json::Value(666);
        arrayObj["datexx"] = ne
        w_item;

        arrayObj["a"].append(new_item);  // 插入数组成员  
        arrayObj["a"].append(new_item1); // 插入数组成员
        out = arrayObj.toStyledString();//arrayObj.toStyledString();
        std::cout << out << std::endl;

        new_item["key_array"].append("array_string");
        new_item["key_array"].append(1234);
        out = new_item.toStyledString();//arrayObj.toStyledString();
        std::cout << out << std::endl;

        int root_size = root.size();
        std::cout << "root size " << root_size << std::endl;
    }

    if (read.parse(strValue2, jsonObj)) {
        std::string code;
        if (!jsonObj["Address"].isNull())  // 访问节点,Access an object value by name, create a null member if it does not exist.
            code = jsonObj["Name"].asString();
        std::cout << code << std::endl;
        // 访问节点,Return the member named key if it exist, defaultValue otherwise.
        code = jsonObj.get("uploadid", "null").asString();

        // 得到"files"的数组个数
        int file_size = jsonObj["Address"].size();
        std::cout << " size " << file_size  << std::endl;
        
        file_size = jsonObj["Address"][0].size();
        std::cout << " size " << file_size << std::endl;

//        std::string name = jsonObj["Address"][0].asCString();
//        std::cout << name << std::endl;

        //迭代器获取json的key
        Json::Value myjson = jsonObj["Address"][0];//getJsonFromFile(“test.json”);
        Json::Value::Members members(myjson.getMemberNames());

        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
            const std::string &key = *it;
            std::cout << key << std::endl;
        }


        Json::Value val_address;
        if (file_size >= 1)
            val_address = jsonObj["Address"];


        for (int i = 0; i < file_size; ++i)
        {
            std::string citys = val_address[i]["City"].asString();
            std::cout  << " city " << citys << std::endl;
    /*        Json::Value val_image = jsonObj["files"][i]["images"];
            int image_size = val_image.size();
            for (int j = 0; j < image_size; ++j)
            {
                std::string type = val_image[j]["type"].asString();
                std::string url = val_image[j]["url"].asString();
            }
    */

        }
//        std::string name = jsonObj["Address"].asCString();
//        std::cout << name << std::endl;
    }

//-----------------------------------------
    json::value.type()返回值


JsonValueType    0        The JsonValue object is Null.
Boolean            1        The JsonValue object is a Boolean.
Number            2        The JsonValue object is a Double.
String            3        The JsonValue object is a String.
Array            4        The JsonValue object is an Array.
Object            5        The JsonValue object is an Object.
对象数组    [{}{}]    6
多个对象{,,,}    7

//--
普通的json组合方式:
    Json::Value topobj;
    Json::Value subobj;
    subobj[azColName[i]] = Json::Value(argv[i]); 
    topobj["a"].append(subobj);//topobj.append(subobj); 也行
//#############################

发布了64 篇原创文章 · 获赞 3 · 访问量 4574

猜你喜欢

转载自blog.csdn.net/qq_37631516/article/details/103787192