UE5 读写本地JSON,发送HTTP请求(get)

UE5 读写本地JSON,发送HTTP请求(get)

没有使用插件,就用UE提供的库开发(推荐使用插件VaRest在虚幻商城里有)

		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "EnhancedInput" ,"Json","JsonUtilities","HTTP","HttpServer"});

读写本地JSON

UE5 读写本地JSON,发送HTTP请求(get)_第1张图片
UE5 读写本地JSON,发送HTTP请求(get)_第2张图片
UE5 读写本地JSON,发送HTTP请求(get)_第3张图片

USTRUCT(BlueprintType)
struct FMyJson : public FTableRowBase
{
	GENERATED_BODY()
	UPROPERTY(EditAnywhere, BlueprintReadWrite, DisplayName="timeStr") 
	FString TimeStr;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, DisplayName="Key1") 
	TArray<FString> Key1;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, DisplayName="Key2") 
	TArray<FString> Key2;
};

UCLASS(Blueprintable)
class UE_IVREAL_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable,meta=(WorldContext="WorldContextObject"))
	static void GetJSONStr(FString &jsonStr,const UObject* WorldContextObject);

	UFUNCTION(BlueprintCallable,meta=(WorldContext="WorldContextObject"))
	static void SetJSONStr(FString jsonStr,const UObject* WorldContextObject);
	
	UFUNCTION(BlueprintCallable,meta=(WorldContext="WorldContextObject"))
	static void DuJson(FString jsonStr,const UObject* WorldContextObject,FMyJson &OutMyJson);
	
	UFUNCTION(BlueprintCallable,meta=(WorldContext="WorldContextObject"))
	static void XieJson(FString &outjsonStr,const UObject* WorldContextObject,FMyJson MyJson);
}

void UMyBlueprintFunctionLibrary::GetJSONStr(FString& jsonStr, const UObject* WorldContextObject)
{
	FString RelaPath="JSON/";//相对路径
	FString FileName="yyy.json";//Json文件名
	FString ResultString;//存放读取结果的字符串
	FString AbsolutePath = FPaths::ProjectContentDir() + RelaPath + FileName;
	//UE_LOG(LogTemp,Warning,TEXT("%s"),*AbsolutePath);
	FFileHelper::LoadFileToString(ResultString, *AbsolutePath);//传入结果字符串和绝对路径
	jsonStr=ResultString;
}

void UMyBlueprintFunctionLibrary::SetJSONStr(FString jsonStr, const UObject* WorldContextObject)
{
	FString RelaPath="JSON/";//相对路径
	FString FileName="yyy.json";//Json文件名
	FString AbsolutePath = FPaths::ProjectContentDir() + RelaPath + FileName;
	//UE_LOG(LogTemp,Warning,TEXT("%s"),*AbsolutePath);
	FFileHelper::SaveStringToFile(jsonStr, *AbsolutePath);//传入结果字符串和绝对路径
}

void UMyBlueprintFunctionLibrary::DuJson(FString jsonStr, const UObject* WorldContextObject,FMyJson &OutMyJson)
{
	FMyJson MyJson;
	//GetJSONStr(jsonStr,WorldContextObject);
	// 创建一个Json 阅读器
	TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<TCHAR>::Create(jsonStr);

	// 创建一个Json对象
	TSharedPtr<FJsonObject> JsonObject;

	// 反序列化,将JsonReader里面的数据,传到JsonObject中
	FJsonSerializer::Deserialize(JsonReader, JsonObject);
	
	// 读取单体数据(假设Json数据里有:Time,单条数据)
	FString timeStr = JsonObject->GetStringField("Time");
	MyJson.TimeStr=timeStr;
	//UE_LOG(LogTemp,Warning,TEXT("Time= %s"),*timeStr);
	
	// 读取数组数据(假设Json数据里有:Data,数组数据)
	TArray<TSharedPtr<FJsonValue>> data = JsonObject->GetArrayField("Data");
	for(int i = 0; i < data.Num(); i++)
	{
		FString dataStr = data[i]->AsObject()->GetStringField("key1");
		FString dataStr1 = data[i]->AsObject()->GetStringField("key2");
		MyJson.Key1.Add(dataStr);
		MyJson.Key2.Add(dataStr1);
		//UE_LOG(LogTemp,Warning,TEXT("key1= %s"),*dataStr);
		//UE_LOG(LogTemp,Warning,TEXT("key2= %s"),*dataStr1);
	}
	OutMyJson=MyJson;
}

void UMyBlueprintFunctionLibrary::XieJson(FString &outjsonStr, const UObject* WorldContextObject, FMyJson MyJson)
{
	// 声明一个存储Json内容的字符串
	FString JsonStr;
	//GetJSONStr(JsonStr,WorldContextObject);

	// 创建一个Json编写器
	TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&JsonStr);

	// 声明Json对象写入开始
	JsonWriter->WriteObjectStart();
	JsonWriter->WriteValue(TEXT("Time"), MyJson.TimeStr);

	// 声明Json数组写入开始
	JsonWriter->WriteArrayStart(TEXT("Data"));
	for (int i = 0; i < MyJson.Key1.Num(); i++)
	{
		JsonWriter->WriteObjectStart();
		JsonWriter->WriteValue(TEXT("key1"), MyJson.Key1[i]);
		JsonWriter->WriteValue(TEXT("key2"), MyJson.Key2[i]);
		JsonWriter->WriteObjectEnd();
	}
	JsonWriter->WriteArrayEnd();
	
	JsonWriter->WriteObjectEnd();
	// 停止写入
	JsonWriter->Close();
	
	UE_LOG(LogTemp,Warning,TEXT("%s"),*JsonStr);
	outjsonStr=JsonStr;
}

UE5 读写本地JSON,发送HTTP请求(get)_第4张图片

发送HTTP请求(get)

这个请求是获取某个位置的天气,并获取返回JSON中的值,读取出来。
apispace
UE5 读写本地JSON,发送HTTP请求(get)_第5张图片

可以先用POSTMan先测试
UE5 读写本地JSON,发送HTTP请求(get)_第6张图片

UE5 读写本地JSON,发送HTTP请求(get)_第7张图片

UE5 读写本地JSON,发送HTTP请求(get)_第8张图片


UCLASS(Blueprintable)
class UE_IVREAL_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
public:
	UPROPERTY(EditAnywhere,BlueprintReadOnly)
	FString CurrentF;
	UPROPERTY(EditAnywhere,BlueprintReadOnly)
	FString CurrentTQ;
	
	FHttpServerModule* HttpServerInstance;
	UFUNCTION(BlueprintCallable,meta=(WorldContext="WorldContextObject"))
	void text();
	
	void RequestComplete(FHttpRequestPtr RequestPtr, FHttpResponsePtr ResponsePtr, bool bIsSuccess);

	DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnBossDiedDelegate);
	UPROPERTY(BlueprintAssignable,EditAnywhere)
	FOnBossDiedDelegate FOK;
	
};



void UMyBlueprintFunctionLibrary::text()
{
	//如果是POST就要传给JSON过去,这里我们是GET
	/*FString server_data;
	// 创建json
	// TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(server_data);
	TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&server_data);
	 //开启json 写入
	JsonWriter->WriteObjectStart();
	//写入数据
	//JsonWriter->WriteValue("Content-Type", "application/json;charset=UTF-8");
	//关闭写入
   JsonWriter->WriteObjectEnd();
	//关闭Json 写入
   JsonWriter->Close();*/
	
	// 创建Http 请求
	TSharedRef<IHttpRequest> Request = FHttpModule::Get().CreateRequest();
	// 设置请求头
	Request->SetHeader("Content-Type","application/json;charset=UTF-8");
	Request->SetHeader("X-APISpace-Token","******");//这里要你的Key
	Request->SetHeader("Authorization-Type","apikey");
	//Request->SetHeader("Host","");
	// 设置请求方式
	Request->SetVerb(TEXT("GET"));
	// 请求的链接
	Request->SetURL("https://eolink.o.apispace.com/456456/weather/v001/now?areacode=101010100"); // 服务端预留的测试接口
	// 内容包
	//Request->SetContentAsString(server_data);
	//UE_LOG(LogTemp,Warning,TEXT("%s"),*server_data);
	
	// 设置回调函数
	Request->OnProcessRequestComplete().BindUObject(this, &UMyBlueprintFunctionLibrary::RequestComplete);
	// 发送请求
	Request->ProcessRequest();

}

void UMyBlueprintFunctionLibrary::RequestComplete(FHttpRequestPtr RequestPtr, FHttpResponsePtr ResponsePtr, bool bIsSuccess)
{
	for (FString AllHeader : ResponsePtr->GetAllHeaders())
		UE_LOG(LogTemp,Warning,TEXT("%s"),*AllHeader);
	UE_LOG(LogTemp,Warning,TEXT("%d"),bIsSuccess);
	if (!EHttpResponseCodes::IsOk(ResponsePtr->GetResponseCode())) return;
	UE_LOG(LogTemp,Warning,TEXT("%d"),bIsSuccess);
	// 获得返回的json数据
	TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ResponsePtr->GetContentAsString());
	// 把FString转成TCHAR
	TCHAR* serializedChar = ResponsePtr->GetContentAsString().GetCharArray().GetData();
	// 解决中文乱码问题,服务端也是utf-8
	TCHAR_TO_UTF8(serializedChar);
	FString myData(serializedChar);
	// 打印信息
	//FWHelper::Debug(myData);
	// 创建Json对象
	TSharedPtr<FJsonObject> JsonObject;
	// 反序列化json
	bool bIsOk = FJsonSerializer::Deserialize(JsonReader, JsonObject);
	// 判断是否反序列化成功
	if (bIsOk)
	{
		FString data = JsonObject->GetStringField("status");
		//FWHelper::Debug(data);
		UE_LOG(LogTemp,Warning,TEXT("%s"),*data);
		UE_LOG(LogTemp,Warning,TEXT("%s"),*myData);
		
		FString OutputString;
		TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> Writer = 	TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&OutputString);
		FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer); //Serialize:把内存中的对象转为便于存储和传输的数据
		//打印
		UE_LOG(LogNet, Warning, TEXT("output 1:\n%s"), *OutputString);
		
		TSharedPtr<FJsonObject, ESPMode::ThreadSafe> Object = JsonObject->GetObjectField(TEXT("result"));
		TSharedPtr<FJsonObject, ESPMode::ThreadSafe> ObjectField = Object->GetObjectField(TEXT("realtime"));
		FString StringField = ObjectField->GetStringField("text");
		CurrentTQ=StringField;
		FString StringField1 = ObjectField->GetStringField("wind_dir");
		CurrentF=StringField1;
		UE_LOG(LogNet, Warning, TEXT("output 1:\n%s"), *StringField);
		FOK.Broadcast();
	}
}

因为是在蓝图函数库,我们需要这样调用
UE5 读写本地JSON,发送HTTP请求(get)_第9张图片

你可能感兴趣的:(UE4,C++,ue5,json,http)