C/C++由字串轉JSON/JSON轉字串/數組解析/數組添加

來源:互聯網
上載者:User

標籤:use   char   字串   pen   font   cpp   print   namespace   字元   

字串轉成JSON(其中str為字串)

Json::Reader Reader;Json::Value DevJson;Reader.parse(str,DevJson);int dev_id = DevJson["dev_id"].asInt();int index = DevJson["index"].asInt();

  

JSON轉字串(其中DevStr為字串)

 Json::Value DevJson = DevsJson[i]; std::string DevStr = DevJson.toStyledString(); printf("Msg:%s", DevStr.c_str());

  

JSON數組解析:

Json::Reader Reader; Json::Value DevsJson; Reader.parse(MsgStr, DevsJson); int siNum = DevsJson.size(); for(int i=0; i < siNum; i++) { Json::Value DevJson = DevsJson[i]; std::string DevStr = DevJson.toStyledString(); printf("Msg:%s", DevStr.c_str()); }

  

數組添加:

 Json::Value root; Json::Value person; person["name"] = "hello world"; person["age"] = 100; root.append(person);

  

結果:[{"age":100,"name":"hello world"}]

---------------------------------------------------

// MyTest.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include "iostream"#include "time.h"#include "map"#include <windows.h>#include <sstream>#include <list>#include "json\json.h"  #include "stdint.h"using namespace std;int _tmain(int argc, _TCHAR* argv[]){Json::Value value;uint32_t ssrc1 = 5305490;value["ssrc1"] = ssrc1;uint32_t ssrc2 = 2152748638;value["ssrc2"] = ssrc2;std::string body = value.toStyledString();cout << body << endl;Json::Reader reader;Json::Value data;reader.parse(body, data, false);if (data.isMember("ssrc1")){cout << "ssrc1";if (data["ssrc1"].isInt())cout << " is Int" << endl;if (data["ssrc1"].isUInt())cout << " is UInt" << endl;}if (data.isMember("ssrc2")){cout << "ssrc2";if (data["ssrc2"].isInt())cout << " is Int" << endl;if (data["ssrc2"].isUInt())cout << " is UInt" << endl;}uint32_t ssrc11 = data["ssrc1"].asUInt();uint32_t ssrc21 = data["ssrc2"].asUInt();cout << "ssrc11:" << ssrc11 << endl;cout << "ssrc21:" << ssrc21 << endl;system("pause");return 0;}

輸出結果:

 

C/C++由字串轉JSON/JSON轉字串/數組解析/數組添加

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.