UE byte 解析 JSON
时间: 2023-07-24 15:29:41 浏览: 59
解析 JSON 字符串可以使用许多库,比如 RapidJSON、nlohmann/json 等。这里以 RapidJSON 为例,给出一个简单的解析器示例。
假设有以下 JSON 字符串:
```json
{
"name": "Alice",
"age": 25,
"isStudent": true,
"grades": [85, 92, 78]
}
```
首先需要定义一个解析器对象:
```c++
#include "rapidjson/document.h"
using namespace rapidjson;
Document doc;
```
然后将 JSON 字符串传入解析器:
```c++
const char* jsonStr = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"grades\":[85,92,78]}";
doc.Parse(jsonStr);
```
这样就可以将 JSON 字符串解析成一个 Document 对象。接下来就可以通过 Document 对象来访问 JSON 数据了。
例如,要访问 name 字段的值:
```c++
std::string name = doc["name"].GetString();
```
要访问 age 字段的值:
```c++
int age = doc["age"].GetInt();
```
要访问 isStudent 字段的值:
```c++
bool isStudent = doc["isStudent"].GetBool();
```
要访问 grades 数组中的第二个元素:
```c++
int grade = doc["grades"][1].GetInt();
```
这样就完成了一个简单的 JSON 解析器。当然,RapidJSON 还提供了更多的 API 和功能,可以根据具体需求进行选择和使用。