用jsoncpp解析JSON字符串

用jsoncpp解析JSON字符串,第1张

用jsoncpp解析JSON字符串

您的问题是:没有 root [“ name”] 。您的文档应如下所示:

{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]}

和你的代码是这样的:

void depre(){    string text ="{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]}";    Json::Value root;    Json::Reader reader;    bool parsingSuccessful = reader.parse( text, root );    if ( !parsingSuccessful )    {        cout << "Error parsing the string" << endl;    }    const Json::Value mynames = root["people"];    for ( int index = 0; index < mynames.size(); ++index )    {        cout << mynames[index] << endl;    }}

如果您想按原样保留数据:

void depre(){  //string text ="{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]}";  string text ="{ "1": {"name":"MIKE","surname":"TAYLOR"}, "2": {"name":"TOM","surname":"JERRY"} }";  Json::Value root;  Json::Reader reader;  bool parsingSuccessful = reader.parse( text, root );  if ( !parsingSuccessful )  {    cout << "Error parsing the string" << endl;  }  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )  {    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )    {      cout << inner.key() << ": " << *inner << endl;    }  }}

使用迭代器直接遍历根对象(不要将其视为数组

如果 Json :: Reader 不起作用,请尝试使用 Json :: CharReader

void depre(){  string text ="{"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}}";  Json::CharReaderBuilder builder;  Json::CharReader * reader = builder.newCharReader();  Json::Value root;  string errors;  bool parsingSuccessful = reader->parse(text.c_str(), text.c_str() + text.size(), &root, &errors);  delete reader;  if ( !parsingSuccessful )  {    cout << text << endl;    cout << errors << endl;  }  for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ )  {    for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ )    {      cout << inner.key() << ": " << *inner << endl;    }  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674094.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存