UE4 C++学习笔记之读取Json

任务:通过指令读取Json文件并打印相应Log

第一步:工程名.Build.cs文件中添加相关依赖("Json", "JsonUtilities");

UE4 C++学习笔记之读取Json_第1张图片

第二步:在PlayerController类中添加相关函数;

EJsonPlayerController.h代码如下:

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "EJsonPlayerController.generated.h"

/**
 * 
 */
UCLASS()
class JSONTEST_API AEJsonPlayerController : public APlayerController
{
	GENERATED_BODY()

public:
	UFUNCTION(Exec) //Exec关键字表示该函数可在游戏运行时通过输入指令运行
		void TestJson(FString InJsonFile);
};

EJsonPlayerController.cpp代码如下:

// Fill out your copyright notice in the Description page of Project Settings.


#include "EJsonPlayerController.h"
#include "json.h"
#include "Engine.h"

void AEJsonPlayerController::TestJson(FString InJsonFile)
{
	FString JsonString;

	//判断文件是否载入成功
	bool bLoadSuccess = FFileHelper::LoadFileToString(JsonString, *InJsonFile);
	if (!bLoadSuccess)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("Loading failed: [%s]!!"), *InJsonFile));
		return;
	}

	//将文件读取至JsonReader中
	TSharedRef> JsonReader = TJsonReaderFactory::Create(JsonString);
	TSharedPtr JsonObject;
	bool bSuccess = FJsonSerializer::Deserialize(JsonReader, JsonObject);
	if (!bSuccess)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("Parseing failed: [%s]!!"), *InJsonFile));
		return;
	}

	if (InJsonFile.Contains(TEXT("p"))) //判断文件名是否包括字符'p'
	{
		TArray> JsonValue = JsonObject->GetArrayField(TEXT("students"));  //读取key为"students"的数组到Json中
		for (auto j : JsonValue)
		{			
			FString msg = FString::Printf(TEXT("Name is %s"), *(j.Get()->AsObject()->GetStringField("Name")));
			GLog->Log("NPC", ELogVerbosity::Log, *msg);
		}
	}
	else
	{
		TSharedPtr Datas = JsonObject->GetObjectField(TEXT("001"));  //读取key为"001"的对象到Datas中
		TMap> Values = Datas.Get()->Values;	 //获取Datas中的TMap
		for (auto kv : Values)
		{
			FString msg = FString::Printf(TEXT("Key = [%s],Value = [%s]"), *(kv.Key), *(kv.Value.Get()->AsString()));
			GLog->Log("NPC", ELogVerbosity::Log, *msg);
		}
	}
}

第三步:创建Json文件,运行程序,读取Json

npc.json内容如下:

{"students":[{"Name":"jack","Adress":"HuBei"},{"Name":"john","Adress":"BeiJing"}]}

读取npc.json结果如下:

UE4 C++学习笔记之读取Json_第2张图片

book.json内容如下:

{
"001":{"书名":"C++ Primer","作者":"Stanley","价格":"128"},
"002":{"书名":"UE4入门经典","作者":"阿拉姆","价格":"89"}
}

读取book.json结果如下:

UE4 C++学习笔记之读取Json_第3张图片

 

你可能感兴趣的:(UE4,C++学习笔记,c++,json,UE4)