json c++处理学习

转自:https://blog.csdn.net/weikangc/article/details/46125107

http://www.codebaoku.com/it-c/it-c-214025.html

https://www.tutorialspoint.com/json/json_data_types.htm

https://blog.csdn.net/fan_music/article/details/82977824

 

初始化一个

#include <iostream>
#include <vector>
#include <map>
#include "jsoncpp/reader.h"
#include "jsoncpp/writer.h"
#include<typeinfo>

using namespace std;

//g++ -std=c++11 json.cpp -I json
int main(){
Json::Reader reader;
Json::Value val;
// string jstr="{\"code\":0,\"data\":{\"cursor\":5, \"list\":[{\"id\":1},{\"id\":2}]}}";
// if(!reader.parse(jstr, micRet, false)){
// cout<<"error!";
// }
{"code":0,"data":{"cursor":5,"list":[{"id":1},{"id":1}]}}
val["code"]=Json::Value(0);

Json::Value data;
data["cursor"]=Json::Value(5);

Json::Value list;
Json::Value list1;
list1["id"]=Json::Value(1);
Json::Value list2;
list2["id"]=Json::Value(1);
list.append(list1);
list.append(list2);

data["list"]=Json::Value(list);
val["data"]=Json::Value(data);

string jstr = Json::FastWriter().write(val);
cout<<jstr<<endl;
return 0;
}

2.从json数组中删除指定的元素

https://avmedia.0voice.com/?id=50776,https://open-source-parsers.github.io/jsoncpp-docs/doxygen/class_json_1_1_value.html#a64160c23c1f2f8b33913364f25d6c58d

{
    // 创建一个JSON对象
    Json::Value root;
    
    // 向JSON对象添加一个数组
    root["array"] = Json::Value(Json::arrayValue);
    root["array"].append("item1");
    root["array"].append("item2");
    root["array"].append("item3");
    std::cout << "原始JSON对象:" << std::endl;
    std::cout << root.toStyledString() << std::endl;
    // 删除数组中的某个元素
    if (root.isMember("array")) {
        for (int i = 0; i < root["array"].size(); ++i) {
            if (root["array"][i].asString() == "item2") {
                root["array"].removeIndex(i, &root["array"][i]);
                break;
            }
        }
    }
    std::cout << "移除数组元素后的JSON对象:" << std::endl;
    std::cout << root.toStyledString() << std::endl;
}

运行结果:
原始JSON对象:
{
        "array" : 
        [
                "item1",
                "item2",
                "item3"
        ]
}

移除数组元素后的JSON对象:
{
        "array" : 
        [
                "item1",
                "item3"
        ]
}

接口介绍:

bool Json::Value::removeIndex(ArrayIndex index, Value *removed);
//Remove the indexed array element. removed 参数存储被删除的元素值
//O(n) expensive operations. Update 'removed' iff removed. 复杂度较高
// Returns true if removed (no exceptions)

可以自定义一个变量存储被删除的元素:

Json::Value root;
Json::Value delete;
root.removeIndex(num,&delete);

3.遍历array数组 

    string strMsg = "{\"student\": [{\"name\":\"张三\",\"age\" : 20}, {\"name\": \"李四\",\"age\" : 18}, {\"name\": \"Mike\",\"age\" : 25}]}";
    
    Json::Value root;
    Json::Reader reader;
    
    /// 解析
    if (!reader.parse(strMsg, root))
    {
        cout << "parse json fail!" << endl;
        return 0; 
    }
    cout<<root.toStyledString()<<"\n";
    /// 打印信息
    Json::Value student_json = root["student"];
    for (int i = 0; i < student_json.size(); i++)
    {
        // https://blog.csdn.net/zilong2015/article/details/79129721
        /// 获得键名
        // Json::Value::Members就是vector<string>类型
        Json::Value::Members keys = student_json[i].getMemberNames();
        for (int j = 0; j < keys.size(); j++)
        {
            string strKey = keys[j];
            string strValue = "";
    
            Json::Value value = student_json[i][strKey];
            if (value.isString())
            {
                strValue = value.asString();
            }
            else if (value.isInt())
            {
                strValue = std::to_string(value.asInt());
            }
            /// to do... 其他类型
        
            cout << "key:" << strKey << " | value:" << strValue << endl;
        }
        cout << "----------------------------------" << endl;
    }
    cout << "----------------------------------" << endl;
    for (int i = 0; i < student_json.size(); i++)
    {
        /// 获得键名
        // 直接使用向量类型也ok
        vector<string> keys = student_json[i].getMemberNames();
        // 使用迭代器遍历
        for (auto iter = keys.begin(); iter!=keys.end();iter++)
        {
            string strKey = *iter;
            string strValue = "";
    
            Json::Value value = student_json[i][strKey];
            if (value.isString())
            {
                strValue = value.asString();
            }
            else if (value.isInt())
            {
                strValue = std::to_string(value.asInt());
            }
            /// to do... 其他类型
        
            cout << "key:" << strKey << " | value:" << strValue << endl;
        }
        cout << "----------------------------------" << endl;
    }

// 输出结果:
{
        "student" : 
        [
                {
                        "age" : 20,
                        "name" : "\u5f20\u4e09"
                },
                {
                        "age" : 18,
                        "name" : "\u674e\u56db"
                },
                {
                        "age" : 25,
                        "name" : "Mike"
                }
        ]
}

key:age | value:20
key:name | value:张三
----------------------------------
key:age | value:18
key:name | value:李四
----------------------------------
key:age | value:25
key:name | value:Mike
----------------------------------
----------------------------------
key:age | value:20
key:name | value:张三
----------------------------------
key:age | value:18
key:name | value:李四
----------------------------------
key:age | value:25
key:name | value:Mike
----------------------------------

 

4.打印json字符串

转自:https://blog.csdn.net/tanningzhong/article/details/96270076

    std::string strTime = "2019-07-11 14:49:14.848715";
    Json::Value root;
    root["Time"] = strTime;
    root["seq"] = 1;
    root["EnCode"] = "H";
    root["Body"] = "ADFASSASDFUUOOOMNNNNAGUAEGEEAE";
    std::string data = root.toStyledString();
    std::cout << data << std::endl;

    Json::FastWriter writer;
    std::string strJson1 = writer.write(root);
    std::cout << strJson1 << std::endl;

// 以上2种方式打印,输出结果:
{
        "Body" : "ADFASSASDFUUOOOMNNNNAGUAEGEEAE",
        "EnCode" : "H",
        "Time" : "2019-07-11 14:49:14.848715",
        "seq" : 1
}

{"Body":"ADFASSASDFUUOOOMNNNNAGUAEGEEAE","EnCode":"H","Time":"2019-07-11 14:49:14.848715","seq":1}

toStyledString()方法会格式化json输出,会在后面添加\r\n之类的字符串,让json串输出好看,而write方法则不会,输出比较原始。

posted @ 2022-09-28 15:45  lypbendlf  阅读(36)  评论(0编辑  收藏  举报