Windows10 VS2017 C++ Json解析(使用jsoncpp库)

1.项目必须是win32
2.生成的lib_json.lib放到工程目录下
3.incldue的头文件放到工程目录,然后设置工程->属性->配置属性->vc++目录->包含目录
4.工程->属性->配置属性->c/c+±>代码生成->运行库,设置运行库为多线程调试 (/MTd)

首先从github下载最新版jsoncpp,0.10.7
https://github.com/open-source-parsers/jsoncpp/releases
在makefile目录的msvc2010打开工程进行编译,将库文件makefiles\msvc2010\Debug\lib_json.lib添加到工程目录,如上步骤2,然后将include目录拷贝到工程目录,按照上边步骤3设置,然后如上步骤4调整设置
解析字符串json,写码:

#include "pch.h"
#include <iostream>
#include <json.h>

#pragma comment(lib, "lib_json.lib")

using namespace std;

int main()
{
	const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";

	Json::Reader reader;
	Json::Value root;
	if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素  
	{
		std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"  
		int code = root["code"].asInt();    // 访问节点,code = 100 
		cout << "upload_id: " << upload_id << endl;
		cout << "code: " << code << endl;
	}
}

在这里插入图片描述

参考文章:
http://www.cnblogs.com/liaocheng/p/4243731.html
https://blog.csdn.net/shufac/article/details/52710100

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要在C++使用JsonCpp来读取JSON文件,你可以按照以下步骤进行操作: 1. 首先,确保已经下载并安装了JsonCpp,并将其包含在你的项目中。 2. 创建一个Json::Value对象来存储解析后的JSON数据。 3. 使用Json::Reader对象来读取JSON文件并解析Json::Value对象。 下面是一个简单的示例代码,演示了如何使用JsonCpp读取JSON文件: ```cpp #include <iostream> #include <fstream> #include <json/json.h> int main() { // 读取 JSON 文件 std::ifstream jsonFile("example.json"); if (!jsonFile.is_open()) { std::cout << "Failed to open JSON file." << std::endl; return 1; } // 解析 JSON 数据 Json::Value root; Json::Reader reader; if (!reader.parse(jsonFile, root)) { std::cout << "Failed to parse JSON data." << std::endl; return 1; } // 读取 JSON 数据并输出 std::string name = root["name"].asString(); int age = root["age"].asInt(); std::string city = root["city"].asString(); std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "City: " << city << std::endl; return 0; } ``` 在上面的示例中,我们首先打开了一个名为`example.json`的JSON文件,然后使用JsonCppJson::Reader对象解析JSON数据,并将其存储在名为`root`的Json::Value对象中。接下来,我们通过访问`root`对象的键值对来获取JSON数据,并将其输出到控制台上。 请确保将示例代码中的`example.json`替换为你实际使用JSON文件的路径。 这里提供一个CSDN上的相关教程供参考:[https://blog.csdn.net/qq_41453285/article/details/105808014](https://blog.csdn.net/qq_41453285/article/details/105808014)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值