UE4 BluePrint 使用 Json
标签:
ue4blueprintjson蓝图转换 |
分类: unreal4 |
Json经常用来服务端和客户端通信而当前UE4发布版本4.8.0
并不支持在蓝图中使用Json,C++源码是有Json支持的,所以我们需要封装一下使得蓝图可用Json。要特别注意UE4
现在支持的是UStruct 和 Json互转,而蓝图中用的是UScriptStruct,所以并不一样,需要自己手动的写这部分的解析代码
- -# (蛋疼 为啥不都支持一下)
UE4 论坛的相关内容也很少,比较有参考意义的是这篇讨论
https://forums.unrealengine.com/showthread.php?56537-Tutorial-How-to-accept-wildcard-structs-in-your-UFUNCTIONs
主体思想就是手动解析UStriptStruct,那么如何手动解析呐,
1、添加手工解析的标识符 CustomStructureParam
2、 阻止UBT不自动生成解析代码 CustomThunk
形如:
static void Generic_ConvertStructToJsonStr(void* Structure,
const UStructProperty* StructProperty, FString& OutStr);
DECLARE_FUNCTION(execConvertStructToJsonStr)
{
Stack.StepCompiledIn(NULL);
void* Structure = Stack.MostRecentPropertyAddress;
UStructProperty* StructProperty =
(UStructProperty*)Stack.MostRecentProperty;
P_GET_PROPERTY_REF(UStrProperty, OutStr);
P_FINISH;
Generic_ConvertStructToJsonStr(Structure, StructProperty,
OutStr);
}
UFUNCTION(BlueprintCallable, CustomThunk, meta = (DisplayName
= "ConvertJsonStrToStruct", CustomStructureParam = "Structure"),
Category = "Json")
static void ConvertJsonStrToStruct(const FString& Instr,
int32 Structure);
static void Generic_ConvertJsonStrToStruct(const FString&
inStr, void* Structure, const UStructProperty*
StructProperty);
DECLARE_FUNCTION(execConvertJsonStrToStruct)
{
P_GET_PROPERTY(UStrProperty, InString);
Stack.StepCompiledIn(NULL);
void* Structure = Stack.MostRecentPropertyAddress;
UStructProperty* StructProperty =
(UStructProperty*)Stack.MostRecentProperty;
P_FINISH;
Generic_ConvertJsonStrToStruct(InString, Structure,
StructProperty);
}
其中Generic_ConvertStructToJsonStr
和 Generic_ConvertJsonStrToStruct
里面添加解析代码
解析部分代码太多就不贴出来,最后能支持所有类型
枚举,整形,布尔,字符串,数组, 而且支持struct的嵌套,完全满足客户端和服务端通信所用。大家可以参考UE4
JsonUtilities 里面对ustruct转json的代码, UStriptStuct 和
Json的互转代码比较类似。还有一点比较恶心 就是UScriptStruct
生成的Key后面带了一大串自动生成的后缀,但是通信中肯定不能有 所以需要你自己手动截掉 -
-~
蓝图中测试调用:

加载中…