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

字符串轉成JSON(其中str爲字符串)ios

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

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

  

JSON數組解析:windows

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"}]app

---------------------------------------------------ui

// 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;
}

輸出結果:spa

 

相關文章
相關標籤/搜索