C++ 如何在 Qt5 中创建/读取/写入 JSon 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15893040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:52:23  来源:igfitidea点击:

How to create/read/write JSon files in Qt5

c++jsonqtqt5

提问by Jim Kieger

Qt5 has a new JSon parser and I want to use it. The problem is that it isn't too clear about what the functions do in layman's terms and how to write code with it. That or I could be reading it wrong.

Qt5 有一个新的 JSon 解析器,我想使用它。问题在于,外行人对这些函数的作用以及如何用它编写代码并不太清楚。那或者我可能读错了。

I want to know the code on creating a Json file in Qt5 and what "encapsulates" mean.

我想知道在 Qt5 中创建 Json 文件的代码以及“封装”是什么意思。

回答by Umasankar Natarajan

Example: Read json from file

示例:从文件中读取 json

/* test.json */
{
   "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
   },
   "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
   }
}


void readJson()
   {
      QString val;
      QFile file;
      file.setFileName("test.json");
      file.open(QIODevice::ReadOnly | QIODevice::Text);
      val = file.readAll();
      file.close();
      qWarning() << val;
      QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
      QJsonObject sett2 = d.object();
      QJsonValue value = sett2.value(QString("appName"));
      qWarning() << value;
      QJsonObject item = value.toObject();
      qWarning() << tr("QJsonObject of description: ") << item;

      /* in case of string value get value and convert into string*/
      qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
      QJsonValue subobj = item["description"];
      qWarning() << subobj.toString();

      /* in case of array get array and convert into string*/
      qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
      QJsonArray test = item["imp"].toArray();
      qWarning() << test[1].toString();
   }


OUTPUT

输出

QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
"QJsonObject[appName] of description: " QJsonValue(string, "Home") 
"Home" 
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
"best" 


Example: Read json from string

示例:从字符串中读取 json

Assign json to string as below and use the readJson()function shown before:

将 json 分配给字符串,如下所示,并使用readJson()之前显示的函数:

val =   
'  {
       "appDesc": {
          "description": "SomeDescription",
          "message": "SomeMessage"
       },
       "appName": {
          "description": "Home",
          "message": "Welcome",
          "imp":["awesome","best","good"]
       }
    }';


OUTPUT

输出

QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
"QJsonObject[appName] of description: " QJsonValue(string, "Home") 
"Home" 
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
"best" 

回答by Jan Kundrát

An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.

一个关于如何使用它的例子会很棒。Qt 论坛上有几个示例,但您应该扩展官方文档是对的。

QJsonDocumenton its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject, QJsonArrayand QJsonValueclasses. The top-level item needs to be either an array or an object (because 1is not a valid json document, while {foo: 1}is.)

QJsonDocument其本身确实不会产生任何东西,您必须向其中添加数据。这是通过QJsonObject,QJsonArrayQJsonValue类完成的。顶级项必须是数组或对象(因为1不是有效的 json 文档,{foo: 1}而是。)

回答by Dr. Alex RE

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

遗憾的是,许多 JSON C++ 库的 API 使用起来并不简单,而 JSON 旨在易于使用。

So I tried jsoncppfrom the gSOAP toolson the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

所以,我试图jsoncppgSOAP的工具上在上面的答案中的一个所示的JSON doc和这与jsoncpp产生构建JSON对象在C ++中,然后写在JSON格式的代码的std :: COUT:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VALas needed):

这是 jsoncpp 生成的代码,用于从 std::cin 解析 JSON 并提取其值(USE_VAL根据需要替换):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

此代码使用 gSOAP 2.8.28 的 JSON C++ API。我不希望人们改变库,但我认为这种比较有助于正确看待 JSON C++ 库。