C++解析Json

本文介绍了JSON的基本概念及其在C++中的使用方法。通过详细步骤展示了如何搭建环境并使用JsonCpp库进行JSON数据的读取与写入操作。

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

一、简单介绍

JSON 的全称为:JavaScript Object Notation。

JSON 是用于标记 Javascript 对象的。

JSON 官方的解释为:JSON 是一种轻量级的数据传输格式,我们将它理解为一种数据类型就好。

其格式一般如下(下面程序会有例子)

{

     “Name“:“Json”,

     "Year":"1994",

     "Sex":"MAN",

     "Other":

      {

          "Height":"180",

           "Weight":"150"

       },

      "Parent":

      [

          {"Father":"C++"},

          {"Mother":"C"}

       ]

}

二、下载JsonCPP,生成可以使用的lib文件

1.从http://jsoncpp.sourceforge.net/下载得到jsoncpp-master.zip,解压

网上的做法:在jsoncpp-src-0.5.0/makefiles/vs71目录里找到jsoncpp.sln,用VS2003及以上版本编译,默认生成静态链接库,本人试了生成不了,于是采用步骤2

2.新建Win32工程,命名为JsonLib,应用程序类型选择静态库,取消预编译头,如下


2.将jsoncpp-master文件夹中的include中的Json文件夹复制到你的工程目录下

3.jsoncpp-master文件夹中的src中的lib_json文件夹中的文件复制到你的工程目录下,最终工程拥有的文件如下:


4.如下图将对应文件引入工程


5.生成-重新生成解决方案,即可生成所需的JsonLib.lib

三、C++调用Jsoncpp

1.新建控制台程序工程JsonTest

2.将jsoncpp-master文件夹中的include中的Json文件夹和JsonLib.lib复制到你的工程目录下

3.项目-属性-链接器-输入-附件依赖项,添加JsonLib.lib

4.如下图将对应文件引入工程


5.JsonTest.cpp的代码如下:

#include "stdafx.h"
#include "json/json.h"
#include <iostream>
using namespace std;

using namespace std;
Json::Reader reader;
Json::Value value;

int _tmain(int argc, _TCHAR* argv[])
{
	string strValue = "{\"name\":\"json\",\"Year\":1994,\"Sex\":\"Man\",\"others\":{\"Height\":180,\"Weight\":150},\"Parents\":[{\"Father\":\"C++\"},{\"Mother\":\"C\"}]}";

	if (reader.parse(strValue, value))
	{
		Json::FastWriter fast_writer;
		cout << fast_writer.write(value) <<endl;

		string out = value["name"].asString();
		cout<<out <<endl;
		out = value["Year"].asString();
		cout<<out <<endl;
		out = value["Sex"].asString();
		cout<<out <<endl;
		out = value["others"]["Height"].asString();
		cout<<out <<endl;
		out = value["others"]["Weight"].asString();
		cout<<out <<endl;
		const Json::Value arrayObj = value["Parents"];
		for (unsigned int i = 0; i < arrayObj.size(); i++)
		{
			if (arrayObj[i].isMember("Father")) 
			{
				out = arrayObj[i]["Father"].asString();
				cout<<out <<endl;
			}
			if (arrayObj[i].isMember("Mother")) 
			{
				out = arrayObj[i]["Mother"].asString();
				cout<<out <<endl;
			}
		}
	}


	Json::Value json_temp;
	json_temp["Height"] = Json::Value(180);
	json_temp["Weight"] = Json::Value(150);

	Json::Value Parents,Mother,Father;
	Father["Father"] = Json::Value("C++");
	Mother["Mother"] = Json::Value("C");
	Parents.append(Father);
	Parents.append(Mother);

	Json::Value root;
	root["name"] = Json::Value("json");
	root["Year"] = Json::Value(1994);
	root["Sex"] = Json::Value("Man");
	root["others"] = json_temp;
	root["Parents"] = Parents;
	Json::FastWriter fast_writer;
	cout << fast_writer.write(root) <<endl;



	return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值