菜鸟笔记
提升您的技术认知

C++解析json数据

jsoncpp 使用详解:
转载:使用 C++ 处理 JSON 数据交换格式

jsoncpp 使用详解
    jsoncpp 主要包含三种类型的 class:Value、Reader、Writer。jsoncpp 中所有对象、类名都在 namespace Json 中,包含 json.h 即可。
    Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 unicode 编码的,最好加一个 Adapt 类来适配。

1、Value
    Json::Value 是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见 Json::ValueType 枚举值。

可如下是用 Json::Value 类:
Json::Value json_temp;      // 临时对象,供如下代码使用
json_temp["name"] = Json::Value("huchao");
json_temp["age"] = Json::Value(26);

Json::Value root;  // 表示整个 json 对象
root["key_string"] = Json::Value("value_string"); 	// 新建一个 Key(名为:key_string),赋予字符串值:"value_string"。
root["key_number"] = Json::Value(12345);           	// 新建一个 Key(名为:key_number),赋予数值:12345。
root["key_boolean"] = Json::Value(false);         	// 新建一个 Key(名为:key_boolean),赋予bool值:false。
root["key_double"] = Json::Value(12.345);          	// 新建一个 Key(名为:key_double),赋予 double 值:12.345。
root["key_object"] = Json_temp;                   	// 新建一个 Key(名为:key_object),赋予 json::Value 对象值。
root["key_array"].append("array_string");         	// 新建一个 Key(名为:key_array),类型为数组,对第一个元素赋值为字符串:"array_string"。
root["key_array"].append(1234);                  	// 为数组 key_array 赋值,对第二个元素赋值为:1234。
Json::ValueType type = root.type();              	// 获得 root 的类型,此处为 objectValue 类型。

注:跟C++ 不同,JavaScript 数组可以为任意类型的值,所以 jsoncpp 也可以。
    如上几个用法已经可以满足绝大部分 json 应用了,当然 jsoncpp 还有一些其他同能,比如说设置注释、比较 json 大小、交换 json 对象等,都很容易使用,大家自己尝试吧。
 
2、Writer
如上说了 Json::Value 的使用方式,现在到了该查看刚才赋值内容的时候了,查看 json 内容,使用 Writer 类即可。
Jsoncpp 的 Json::Writer 类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。
顾名思义,用 Json::FastWriter 来处理 json 应该是最快的,下面我们来试试。
Json::FastWriter fast_writer;
std::cout << fast_writer.write(root) << std::endl;

输出结果为:
{
  "key_array":["array_string",1234],"key_boolean":false,"key_double":12.3450,"key_number":12345,"key_object":{
  "age":26,"name":"huchao"},"key_string":"value_string"}

再次顾名思义,用 Json::StyledWriter 是格式化后的 json,下面我们来看看 Json::StyledWriter 是怎样格式化的。
Json::StyledWriter styled_writer;
std::cout << styled_writer.write(root) << std::endl;
输出结果为:
{
  
   "key_array" : [ "array_string", 1234 ],
   "key_boolean" : false,
   "key_double" : 12.3450,
   "key_number" : 12345,
   "key_object" : {
  
      "age" : 26,
      "name" : "huchao"
   },
   "key_string" : "value_string"
}

3、Reader
    Json::Reader 是用于读取的,说的确切点,是用于将字符串转换为 Json::Value 对象的,下面我们来看个简单的例子。
  Json::Reader reader;
  Json::Value json_object;
  const char* json_document = "{/"age/" : 26,/"name/" : /"huchao/"}";
  if (!reader.parse(json_document, json_object))
    return 0;
   
  std::cout << json_object["name"] << std::endl;
  std::cout << json_object["age"] << std::endl;
  
输出结果为:
"huchao"
Json::Value fcgiRetData;
fcgiRetData["name"] = Json::Value("shark");//fcgiRetData["name"] = "string";
fcgiRetData["age"] = 100;
fcgiRetData["msg"] = Json::Value(0);//fcgiRetData["msg"] = "null"
Json::StyledWriter tRet;
std::cout << tRet.write(json_ret) << std::endl;

Json::Value fcgiRetData;
...//获取到fcgiRetData数据
Json::StyledWriter styledWriter;
string response = styledWriter.write(fcgiRetData);//将fcgiRetData的json数据格式化

转载:C++解析JSON格式数据
1:封装JSON数据为string

std::string DataToJson()
{
  
    Json::FastWriter writerinfo;
    Json::Value  writevalueinfo;
 
    writevalueinfo["id"]=123;   
    writevalueinfo["time"]="2017.08.30 00:00:00";
 
    Json::Value  writedata;
    writedata["count"] = 1;
    writedata["name"] = "cpp";
 
    writevalueinfo["data"]=writedata;
 
    std::string strEmail = writerinfo.write(writevalueinfo);
    return strEmail;
}
 
示例json:
{
  
    "data": {
  
        "count": 1,
        "name": "cpp"
    },
    "id": 123,
    "time": "2017.08.30 00:00:00"
}

解析json数据

void TranslateJson(const string strData)
{
  
    // 解析json用Json::Reader
    Json::Reader *readerinfo = new Json::Reader(Json::Features::strictMode());
    // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array...
    Json::Value root;       
    if (readerinfo->parse(strData, root))
    {
  
        if (root["id"].isInt())
        {
  
            int nID = root["id"].asInt();
        }
 
        if (root["time"].isString())
        {
  
            std::string strTime = root["time"].asString();
        }
 
        if (root["data"]["count"].isInt())
        {
  
            int nDataCount = root["data"]["count"].asInt();
        }
 
        if (root["data"]["name"].isString())
        {
  
            std::string strDataName = root["data"]["name"].asString();
        }
 
    }
 
    ::delete readerinfo;
    readerinfo = NULL;
}

2:json数组操作
封装:

Json::Value arrayObj;   // 构建对象
for (int i = 0; i < 3; i++)
{
  
        Json::Value new_item;
        new_item["id"] = i;
        new_item["name"] = "test";
        arrayObj.append(new_item);  // 插入数组成员
}
示例json:
[
    {
  
    "id": 0,
    "name": "test"
    },{
  
    "id": 1,
    "name": "test"
    },
    {
  
    "id": 2,
    "name": "test"
    }
]
 
arrayObj.append(new_item); 改为 arrayObj["array"].append(new_item);
示例json:
{
  
    "array": [
        {
  
            "id": 0,
            "name": "test"
        },
        {
  
            "id": 1,
            "name": "test"
        },
        {
  
            "id": 2,
            "name": "test"
        }
    ]
}

解析:

void TranslateJson(const string strData)
{
  
    // 解析json用Json::Reader
    Json::Reader *readerinfo = new Json::Reader(Json::Features::strictMode());
    // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array...
    Json::Value root;       
    if (readerinfo->parse(strData, root))
    {
  
        //arrayObj.append(new_item);
        if (root.isarray())
        {
  
            int nArraySize = root.size();   
            for (int i=0; i<nArraySize; i++)
            {
         
                int nID = root[i]["id"].asInt();
                std::string strName = root[i]["name"].asString();   
            }
        }
 
 
        // arrayObj["array"].append(new_item);
        if (root["array"].isArray())
        {
  
            int nArraySize = root["array"].size();  
            for (int i=0; i<nArraySize; i++)
            {
         
                int nID = root["array"][i]["id"].asInt();
                std::string strName = root["array"][i]["name"].asString();  
            }
        }
    }
 
    ::delete readerinfo;
    readerinfo = NULL;
}