c++ - QJson for Linux - 不确定如何正确使用 QJSON

标签 c++ linux qt qjson

一些背景

最初在 mac 上做了一个项目,现在我想使用我的 Linux 机器来做同样的项目。设置文件夹依赖:

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonParseError>

这些未包含在我的 SL5 qt-devel 安装中 - 它使用 QT v4。所以我下载了QJson from Sourceforge并使用 cmake 安装。一些示例输出:

--Installing: /usr/include/qjson/parser.h
--Installing /usr/lib/libqjson.so

没关系。所以我添加到我的.pro:

LIBS += -L/usr/lib/ -lqjson
INCLUDEPATH += /usr/include/qjson/

实际问题

现在我的任务是翻译我的旧 settings.cpp文件来解析这个稍微新的方法中的数据。

{
  "HwDescription": {
    "ConnectionsName": "file://settings/connections.xml",
    "ShelveId": 0,
    "BeBoard": {
      "Id": 10,
      "connectionId": "board0",
      "boardType": "GLIB"
    }, // + more boring stuff

所以现在我在 QString 中有这个 json,就像我对旧的工作方法所做的那样,然后我尝试按照给我的说明进行解析。我用过:#include <qjson/parser.h>我认为这里不需要任何前向声明。

    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse (raw_json, &ok).toMap(); //where raw_json is a QString - this is where I get an error
    if (!ok)
    {
      qFatal("An error occured during parsing");
      exit (1);
    }

我得到的错误:

error: no matching function to call to 'Qjson::Parser:parse(QString&, bool)

如果我删除包含内容,则会出现错误:

QJson has not been declared

所以它至少必须找到库。关于出了什么问题有什么想法吗?

最佳答案

QJson 中默认不解析评论。

这是我对 QJson 逻辑进行的一个小修改,用于处理评论。请注意用于删除注释的简单正则表达式。

QFile file( filename );

  //File can't be opened!
if ( !file.open( QFile::ReadOnly ) )
{ 
  qDebug("Couldn't load config file: %s", filename.toLatin1().data());
  return;
} 

  //Strip out comments
QStringList list = QString( file.readAll() ).split('\n');
for ( int i = 0; i < list.size(); i++ )
  list[i].replace( QRegExp("//[^\"]*$"), "" );

//Load the file, converting into an object file
QJsonParseError e;
QJsonObject json = 
  QJsonDocument::fromJson( list.join('\n').toLatin1(), &e ).object();

//Was there an error?
if ( e.error != QJsonParseError::NoError )
{ 
  qDebug( "Json parse error: %s", e.errorString().toLatin1().data() );
  return;
}

关于c++ - QJson for Linux - 不确定如何正确使用 QJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25846759/

相关文章:

c++ - 未知类型名称 'class' ;你的意思是 'Class' 吗?

linux - 如何只替换 Perl 中 IP 地址的前三个八位字节

android - Qt 升级后 QPushButton 有重复的文本

linux - 使用 AWK 在 n 个匹配项之后和 m 个匹配项之前查找并替换

linux - 如何清理目录结构的文件权限

c++ - QRegExp 包含换行符,输入

c++ - 证书链的根证书是自签名的,不受信任的

c++ - 从类中仅调用一次方法

c++ - boost::algorithm::join 返回值的范围是什么?

c++ - 为指针赋值