qt json格式组装和拆解
头文件
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
qt json格式组装
QJsonObject simp_ayjson;
simp_ayjson.insert("name", "LLH");
simp_ayjson.insert("age", 20);
simp_ayjson.insert("myAccounts", QString::fromLocal8Bit("123你好"));
QJsonDocument document;
document.setObject(simp_ayjson);
QByteArray simpbyte_array = document.toJson(QJsonDocument::Compact);
QString simpjson_str(simpbyte_array);
qt json格式拆分
网上的比较麻烦,但是比较安全
如下
//简单的QT解析JSON
QJsonParseError simp_json_error;
QString name, myAccount;
int age;
//QTJSON所有的元素
QJsonDocument simp_parse_doucment = QJsonDocument::fromJson(msg.toUtf8(), &simp_json_error);
//检查json是否有错误
if (simp_json_error.error == QJsonParseError::NoError)
{
if (simp_parse_doucment.isObject())
{
//开始解析json对象
QJsonObject obj = simp_parse_doucment.object();
//如果包含name
if (obj.contains("name"))
{
//的到name
QJsonValue name_value = obj.take("name");
if (name_value.isString())
{
//转换name
name = name_value.toVariant().toString();
}
}
if (obj.contains("myAccounts"))
{
QJsonValue myAccount_value = obj.take("myAccounts");
if (myAccount_value.isDouble())
{
myAccount = myAccount_value.toVariant().toString();
}
}
if (obj.contains("age"))
{
QJsonValue age_value = obj.take("age");
if (age_value.isDouble())
{
age = age_value.toVariant().toInt();
}
}
}
}
qDebug() << QString::fromLocal8Bit("简单的QT解析出来的数据:") << name << "," << age << "," << myAccount;
我自己简化了一些步骤如下(我这里数据格式众多,不可能一一校验,既然我这里使用这个说明肯定有这些字段,就减少了一些校验)
//简单的QT解析JSON
QJsonParseError simp_json_error;
//QTJSON所有的元素
QJsonDocument simp_parse_doucment = QJsonDocument::fromJson(msg.toUtf8(), &simp_json_error);
//检查json是否有错误
if (simp_json_error.error == QJsonParseError::NoError)
{
QJsonObject obj = simp_parse_doucment.object();
//obj.contains("control")?strcpy(pt.control,obj.take("control").toVariant().toString().toLatin1().data()):"";
strcpy(pt.ip1,obj.take("ip1").toVariant().toString().toLatin1().data());
strcpy(pt.ip2,obj.take("ip2").toVariant().toString().toLatin1().data());
pt.port1 = obj.take("port1").toVariant().toString().toInt();
}
do_send(pt,cmdflag);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构