C/C++由字符串转JSON/JSON转字符串/数组解析/数组添加

本文通过C++示例代码展示了如何将字符串转换为JSON对象,反之亦然,并提供了JSON数组的解析方法及如何向JSON数组中添加元素的具体实现。此外,还介绍了如何处理JSON中的整数类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串转成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;
}

输出结果:

 

转载于:https://www.cnblogs.com/blackhumour2018/p/9467232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值