本章简介
- JSON格式
- 解析JSON文件
- 修改JSON文件
JSON格式
想要使用JSO相关工具,必须在ProjectName.Build.cs,在其中添加
PublicDependencyModuleNames.AddRange
(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"InputCore",
"Slate",
"SlateCore",
"Json",
"JsonUtilities"
}
);
解析JSON文件
- 我们在 \Content\Res\Data.json中天下如下测试例子
/** Data.json **/
[
{
"1-1":"1-1",
"1-2":"1-2"
},
{
"2-1":"2-1"
},
{
"3-1":
[
{
"1":"3-1-1"
},
{
"2":"3-1-2"
}
]
}
]
- 我们要首先得将他以字符串的形式读入
FPaths::GameContentDir() 能获取 */Content/ 的位置
FFileHelper::LoadFileToString() Load a text file to an FString.
bool MyJsonHandle::LoadStringFromFile(FString & RelativePathName, FString & FileName, FString & ResultString)
{
if (!FileName.IsEmpty())
{
FString AbsloutePathName = FPaths::GameContentDir() + RelativePathName + FileName;
if (FPaths::FileExists(AbsloutePathName))
{
if (FFileHelper::LoadFileToString(ResultString, *AbsloutePathName))
{
return true;
}
}
}
return false;
}
`
- 接下来我们来解析我们所获取到的FString
/** MyJsonHandle.cpp **/
bool MyJsonHandle::RecordDataJsonRead()
{
FString result;
//这是我们上面自定义的函数
LoadStringFromFile(RelativePathName, DataFileName, result);
TArray<TSharedPtr<FJsonValue>> JsonParse;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(result);
if (FJsonSerializer::Deserialize(JsonReader, JsonParse))
{ //这样解析后的节点全部存在JsonParse中
UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonParse[0]->AsObject()->GetStringField(FString("1-1")));
UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonParse[0]->AsObject()->GetStringField(FString("1-2")));
UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonParse[1]->AsObject()->GetStringField(FString("2-1")));
//如果对象是嵌套的,则需要再声明一次TArray<TSharedPtr<FJsonValue>>来获取
TArray<TSharedPtr<FJsonValue>> JsonParse3 = JsonParse[2]->AsObject()->GetArrayField(FString("3-1"));
if (JsonParse3.IsValidIndex(0))
{
for (int cnt = 1; cnt <= JsonParse3.Num(); ++cnt)
{
UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonParse3[cnt-1]->AsObject()->GetStringField(FString::FromInt(cnt)));
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("error JsonParse3"));
}
return true;
}
return false;
}
修改JSON文件
设置单个属性
- 通过下面的代码生成一个
/** * A Json Object is a structure holding an unordered set of name/value pairs. * In a Json file, it is represented by everything between curly braces {}. */ TSharedPtr<FJsonObject> Object1 = MakeShareable(new FJsonObject); Object1->SetStringField("1-1", "1--1"); Object1->SetStringField("1-2", "1--2"); TSharedPtr<FJsonValueObject> CultureValue = MakeShareable(new FJsonValueObject(CultureObject));