转自:http://blog.csdn.net/cartzhang/article/details/41009343
JSON 的解析有很多开源库。UE4的JSON使用在代码的Public->Serialization中。
头文件包含:Json.h
Json的读写创建是static形成的单例模式,有JsonWrite或JsonReader的Factory来创建(Create)出来。
以读方式为例子:
读的代码:
float _score = MyPlayerState->GetScore(); FString _player_name = MyPlayerState->GetName(); int _kills = MyPlayerState->GetKills(); int _deaths = MyPlayerState->GetDeaths(); FString JsonStr; TSharedRef< TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR> > > JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR> >::Create(&JsonStr); JsonWriter->WriteObjectStart(); JsonWriter->WriteValue(TEXT("name"), _player_name); JsonWriter->WriteValue(TEXT("score"), _score); JsonWriter->WriteValue(TEXT("deaths"), _deaths); JsonWriter->WriteValue(TEXT("kills"), _kills); lt;span style="white-space:pre"> </span>JsonWriter->WriteObjectEnd(); // Close the writer and finalize the output such that JsonStr has what we want JsonWriter->Close(); return JsonStr;
写的对象可以为Objcet或Array数组,value值。
一个读写过程中,Start和End要对应,因为Json格式的要求,要不我怎么知道哪里是一个对象或数组的结尾呢。这样就会造成混乱的。
UE4 的json读写方式
一、UE4的Json解析代码
有网友说UE4的解析有问题,解析出错。个人觉得应该是Json格式有问题。或解析的对象不正确,对象或数组用来对应的解析方式来解析的。
解析方式有两种:类名为:FJsonSerializer,头文件名称为JsonSerializer.h
template <class CharType> static bool Deserialize( const TSharedRef< TJsonReader<CharType> >& Reader, TArray< TSharedPtr<FJsonValue> >& OutArray ) { StackState State; if ( !Deserialize( Reader, /*OUT*/State ) ) { return false; } if ( State.Object.IsValid() ) { return false; } OutArray = State.Array; return true; } template <class CharType> static bool Deserialize( const TSharedRef< TJsonReader<CharType> >& Reader, TSharedPtr<FJsonObject>& OutObject ) { StackState State; if ( !Deserialize( Reader, /*OUT*/State ) ) { return false; } if ( !State.Object.IsValid() ) { return false; } OutObject = State.Object; return true; }
可以看出,第一个是针对数组的,第二个是针对Json对象的。请注意分别。
二、样例代码
CPP中包含头文件#include "Json.h"。
void ATestPhysics1Character::JsonDeserialize() { FString JsonValue = "[{\"author\":\"4446545646544\"},{\"name\":\"jack\"}]"; FString JsonStr; TArray<TSharedPtr<FJsonValue>> JsonParsed; TSharedRef< TJsonReader<TCHAR> > JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonValue); bool BFlag = FJsonSerializer::Deserialize(JsonReader, JsonParsed); if (BFlag) { int ArrayNumber = JsonParsed.Num(); if (ArrayNumber == 2) { FString FStringAuthor = JsonParsed[0]->AsObject()->GetStringField("author"); if (GEngine) { FString TmpString = "author :" + FStringAuthor; GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TmpString); } FString FStringName = JsonParsed[1]->AsObject()->GetStringField("name"); if (GEngine) { FString TmpString = "name :" + FStringName; GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TmpString); } } } }