C++使用Json问题

誰伴我闖荡 2010-06-20 11:02:17
如题,我想使用c++来操作Json。从www.json.org下载了jsoncpp,编译成功。建立新项目,配置好环境。

现在的问题是,我如何将一个简单的对象写入一个特定的文件中,以及如何读取,

现在需要一个简单的示例代码,能够进行简单的读取和写入,越简单越好。

谢谢了。
...全文
1248 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
誰伴我闖荡 2010-06-22
  • 打赏
  • 举报
回复
json_vc71_libmt.lib(json_value.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in stdafx.obj
誰伴我闖荡 2010-06-22
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 zhangweiit 的回复:]

C/C++ code


std::string test = "{\"test\":5,\

\"Value\":{\"version\":\"this is version\"}}";

Json::Reader reader;

Json::Value value;

if(reader.parse(test,value))
{

int i = 0;

……
[/Quote]

我使用的是jsoncpp的库json_vc71_libmt.lib
但是编译Json::Reader reader;这句时,要出错误。
iamwlj 2010-06-22
  • 打赏
  • 举报
回复
json_spirit的例子

//读
std::string line = "{\"username\":\"xman\",\"id\":007}";
json_spirit::Value value;
json_spirit::read(line, value);
if (value.type() != obj_type)
{
return;
}
else
{
int id = 0;
std::string username = "";
const json_spirit::Object &obj = value.get_obj();
for(unsigned int i = 0; i != obj.size(); ++i )
{
const json_spirit::Pair& pair = obj[i];

const string& name = pair.name_;
const json_spirit::Value& vvalue = pair.value_;

if( name == "id" && vvalue.type() == int_type)
{
id = vvalue.get_int();
}
else if( name == "id" && vvalue.type() == str_type)
{
username = vvalue.get_str();
}
}
}

//写
json_spirit::Object robj;
robj.push_back( Pair("id", id));
robj.push_back( Pair("username", username));
std::string output = json_spirit::write_formatted(robj);
// output = line

zhangweiit 2010-06-20
  • 打赏
  • 举报
回复


std::string test = "{\"test\":5,\

\"Value\":{\"version\":\"this is version\"}}";

Json::Reader reader;

Json::Value value;

if(reader.parse(test,value))
{

int i = 0;

bool isNull = value["test"].isNull();

if(!isNull)

i = value["test"].asInt();
if(!value["Value"]["version"].isNull())
{

std::string str = value["Value"]["version"].asString();


}

Json::Value val1= value["OtherKey"];

if(!val1.isNull())

{

i = val1.asInt();

}

}



这个小例子你可以看看

里面,直接用test这个字符串里面的JSON值,当然,这个字符串也可以是从文件中读出来的
zhangweiit 2010-06-20
  • 打赏
  • 举报
回复
你把可以把JSON对象以纯字符写入文件,
在需要用的时候,可以直接从文件读出来的
logiciel 2010-06-20
  • 打赏
  • 举报
回复
jsoncpp-src-0.5.0中子目录src\jsontestrunner中的main.cpp就是一个简单的示例代码。

设有输入文件test.json,其内容是:
{
"name":"zhang san",
"age":24
}

用VS2005打开子目录makefiles\vs71中的jsoncpp.sln,编译连接项目jsontest,就可处理输入文件test.json了,运行后将生成test.actual-rewrite,test.actual,test.rewrite等3个文件。

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧