UE4 中C++读取Json文件

本篇文章介绍C++读取Json文件前我们先了解下Json格式,Json格式不同读取会有所区别(踩了一波坑)

Json文件有三种格式,这三种格式都是正确的。这边提供一个很有用的Json文件在线编辑平台的网址:在线编辑Json网站

Json文件的三种格式如图:

1.

{
    "Name": "张三",
    "Age": 18,
    "hobby": 
    [
        "画画",
        "游泳",
        "羽毛球"
    ],
    "星座": "狮子座",
}

2.

[1,"hello world",null]

3.

[
    {
        "count": 3,
        "xres_ver": "2.0"
    },
    {"Language": [
	    {
		    "Areakey": "china",
		    "ID": 1,
		    "LangName": "中文"
	    },
	    {
		    "Areakey": "taiwan",
		    "ID": 2,
		    "LangName": "中文繁体"
	    },
	    {
		    "Areakey": "en",
		    "ID": 3,
		    "LangName": "english"
	    }
    ]}
]

第一种格式的Json文件读取方式可参考如下代码:

FString filePath =  FPaths::ProjectContentDir() +TEXT("Test.json");
if (!FPaths::FileExists(filePath ))
{
    UE_LOG(LogTemp, Error, TEXT("File Path:%s ,File do not exist"),*filePath);
	return;
}
FString ContentStr;
if (!FFileHelper::LoadFileToString(ContentStr, *filePath ))
{
	UE_LOG(LogTemp, Error, TEXT("File Path:%s ,File Load failed"),*filePath);
	return;
}
TSharedRef> Reader = TJsonReaderFactory::Create(ContentStr);
TSharedPtr rootObject;

bool bSuccess = FJsonSerializer::Deserialize(jsonReader, rootObject);
if (!bSuccess)
{
		UE_LOG(LogTemp, Error, TEXT("Parseing failed: [%s]!!"), *filePath);
		return;
}

FString Name;
if (rootObject->TryGetStringField(TEXT("LogicLevelGroup_cfg"), Name))
{
    UE_LOG(LogTemp, Error, TEXT("people Name: [%s]!!"), *Name)
}

第二、三种格式的Json文件读取方式可参考如下代码:

FString filePath =  FPaths::ProjectContentDir() +TEXT("Test.json");
if (!FPaths::FileExists(filePath ))
{
    UE_LOG(LogTemp, Error, TEXT("File Path:%s ,File do not exist"),*filePath);
	return;
}
FString ContentStr;
if (!FFileHelper::LoadFileToString(ContentStr, *FilePath))
{
	UE_LOG(LogTemp, Error, TEXT("File Path:%s ,File Load failed"),*filePath);
	return;
}
TSharedRef> Reader = TJsonReaderFactory::Create(ContentStr);
TArray> OutArray;

if (FJsonSerializer::Deserialize(Reader, OutArray))
{
	TSharedPtr JsonObject;
	JsonObject = OutArray[1]->AsObject();
	TArray> ConfigArray;
	LanguageArray = JsonObject->GetArrayField("Language");
	for (auto JsonValue : LanguageArray)
    {
    
        TSharedPtritemObjet = item->AsObject();
		FString LangName = itemObjet->GetStringField(TEXT("LangName"))
        UE_LOG(LogTemp, Error, TEXT("Language name:%s"),*LangName);
    }
}

实际上两种解析的区别主要在于对Json文件中类似于字典以及数组 的两种数据结构的区别处理

你可能感兴趣的:(踩坑日记,json,ue4,c++)