前言
在上一篇(【UE5 C++课程系列笔记】31------创建Json并保存为文件)中我们已经将Json存储到Json文件中,本篇会通过读取该Json文件来解析Json。
步骤
- 定义一个函数用于读取Json,这里函数命名为"ReadJson"

函数实现如下,首先加载Json文件从而获得Json字符串

通过Json字符串构建Json对象

解析Json对象中的数字、字符串、Json对象和数组类型

完整代码:
cpp
void ASampleJson::ReadJson()
{
//从文件中获取Json字符串
FString JsonFilePath = FPaths::ProjectSavedDir() / TEXT("GoodJson.json");
FString JsonString = TEXT("");
FFileHelper::LoadFileToString(JsonString, *JsonFilePath);
//通过Json字符串构建Json对象
TSharedPtr<FJsonObject> JsonObject;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonString);
//解析Json
bool IsDeserialize = FJsonSerializer::Deserialize(JsonReader, JsonObject); //判断能否反序列化
if (IsDeserialize)
{
//解析数字
int32 CodeNum = JsonObject->GetNumberField(TEXT("Code"));
//解析字符串
FString Message = JsonObject->GetStringField(TEXT("Message"));
//解析JsonObject
TSharedPtr<FJsonObject> Server = JsonObject->GetObjectField(TEXT("Server"));
FString ServerName = Server->GetStringField(TEXT("ServerName"));
FString ServerVersion = Server->GetStringField(TEXT("ServerVersion"));
//解析数组
TArray<TSharedPtr<FJsonValue>> MyArray = JsonObject->GetArrayField(TEXT("MyArray"));
for (auto& Ele : MyArray)
{
int32 Id = Ele->AsNumber();
}
//解析数组嵌套Json
TArray<TSharedPtr<FJsonValue>> Workers = JsonObject->GetArrayField(TEXT("Workers"));
for (auto& Ele : Workers)
{
TSharedPtr<FJsonObject> Worker = Ele->AsObject();
int32 ID = Worker->GetIntegerField(TEXT("ID"));
FString Name = Worker->GetStringField(TEXT("Name"));
int32 Age = Worker->GetIntegerField(TEXT("Age"));
}
}
}