QT中JSON数据对象嵌套对象怎么写
时间: 2024-09-18 07:02:07 浏览: 46
TCPJsonDataReceiver.rar
在Qt中处理JSON数据,特别是涉及到嵌套的对象,通常使用QJsonDocument、QJsonObject或QJsonValue等工具。嵌套对象可以按照JavaScript风格编写,例如:
```json
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
```
在Qt里,你可以这样做:
```cpp
QJsonObject root;
root.insert("name", QJsonValue::fromString("John Doe"));
root.insert("age", QJsonValue::fromInt(30));
QJsonObject address;
address.insert("street", QJsonValue::fromString("123 Main St"));
address.insert("city", QJsonValue::fromString("New York"));
address.insert("country", QJsonValue::fromString("USA"));
root.insert("address", address);
QJsonDocument document(root);
// 现在document就是包含嵌套对象的JSON文档
```
如果你想从这样的JSON字符串中读取数据,可以使用`fromJson`函数:
```cpp
QString jsonString = R"({"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"New York","country":"USA"}})";
QJsonDocument parsedDoc = QJsonDocument::fromJson(jsonString.toUtf8());
QJsonObject obj = parsedDoc.object();
```
阅读全文