简体   繁体   English

unity Restsharp Api Json 序列化和反序列化

[英]Unity Restsharp Api Json Serialization & Deserialization

I am developing a multiplayer game.我正在开发一个多人游戏。 I have a friend who developing API on Swagger.io.我有一个朋友在 Swagger.io 上开发 API。 So here is my problem:所以这是我的问题:

I want to use Task function that I can use instead of Unity's own UnityWebRequest function.我想使用我可以使用的任务 function 来代替 Unity 自己的 UnityWebRequest function。 I look After doing some research, I wrote the following codes.我在做一些研究后,写了以下代码。

    private async Task<T> Send<T>(string service, object obj)
{
    RestClient client = new RestClient(baseUrl);
    RestRequest request = new RestRequest(service)
    {
        RequestFormat = DataFormat.Json,
        Method = Method.POST,
    };
#if UNITY_ANDROID
        uniqueID = SystemInfo.deviceUniqueIdentifier;
        platform = "1";
#endif
#if UNITY_IOS
        uniqueID = UIDevice.identifierForVendor
        platform = "0";
#endif
        request.AddHeader("DeviceID", uniqueID);
        request.AddHeader("BundleID", Application.identifier);
        request.AddHeader("BuildID", "0");
        request.AddHeader("Platform", platform);
        request.AddHeader("Version", "0");
        request.AddJsonBody(obj);

        var response = await client.ExecuteAsync(request);

        if (response.Content != null && response.StatusCode == HttpStatusCode.OK)
        {
            var jsonSerializerSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore };
            var result = JsonConvert.DeserializeObject<T>(response.Content, jsonSerializerSetting);
            return result;
        }
        else
        {
            return default;
        }

Since it is an async function, I call it with await without any problems.因为它是一个异步 function,所以我用 await 调用它没有任何问题。 Like this:像这样:

I have some class that can response some other class:我有一些 class 可以响应其他一些 class:

[Serializable]
public class WelcomeRequest : Response
{
    public string Location;
    public string Language;
}
[Serializable]
public class WelcomeRequest : Response
{
    public string Location;
    public string Language;
}[Serializable]
public class WelcomeResponse : Response
{
    public WelcomePayload Payload;
}

[Serializable]
public class WelcomePayload : Response
{
    public Player Player;
    public Settings Settings;
    public Season Play;
    public Season Purchase;
    public Game GameOfSeason;
    public Game[] Games;
    public double PrizePool;
}

(I know it's a big project and there are a lot of subclasses. I don't want you to write code for me, I just want you to explain the logic of the code I wrote and an example that I can reference. Not to mention that I'm trying to do it alone. I don't have any friends who can help you but you.) I am able to receive files in json format from the server. (我知道这是一个大项目,子类很多。我不想让你给我写代码,我只是想让你解释一下我写的代码的逻辑和一个我可以参考的例子。不要提到我正在尝试一个人做。除了你我没有任何朋友可以帮助你。)我能够从服务器接收 json 格式的文件。 But since this function only returns the object, I cannot assign sub-objects of the class.但是由于这个 function 只返回 object,我无法分配 class 的子对象。 Do I need to convert it to json format again and deserialize it?我是否需要再次将其转换为 json 格式并反序列化? Since I was working with the Firebase infrastructure before, I was able to communicate without any problems.由于我之前使用的是 Firebase 基础架构,因此我能够毫无问题地进行通信。 I looked for Restsharp Unity tutorials but couldn't find any.我查找了 Restsharp Unity 教程,但没有找到。 Can you help me?你能帮助我吗? At least if you guide me I will try to solve it myself.至少如果你指导我,我会尝试自己解决它。 I'm sorry if I didn't express myself properly as this is my first post on this site and I don't know the rules very well.如果我没有正确表达自己,我很抱歉,因为这是我在这个网站上的第一篇文章,我不太了解规则。 Endless thanks to all of you.无尽的感谢你们。

This doesn't really answer your question but you might want to consider using a generated client.这并不能真正回答您的问题,但您可能需要考虑使用生成的客户端。

If the API is made in swagger you should be able to make a C# API client using openapi-generator and the Swagger Schema. If the API is made in swagger you should be able to make a C# API client using openapi-generator and the Swagger Schema. Then just build the generated project and drop the DLL in the unity projects Assets folder.然后只需构建生成的项目并将 DLL 拖放到统一项目的 Assets 文件夹中。

You probably also need to include RestSharp and Newtonsoft.Json .您可能还需要包括RestSharpNewtonsoft.Json Just download these NuGet packages and unpack them (nupkg files are just zips) the dll should be in there.只需下载这些 NuGet 包并解压缩它们(nupkg 文件只是 zip) dll 应该在那里。 Include it by dropping the DLL in the Assets folder.通过将 DLL 放到 Assets 文件夹中来包含它。

public class Error: Response
{
public string Field; //The name of the area where the problem was detected
public string Error_; //Contains the code for the error message
public string HighLight; //It's used for the data to be highlighted in the error 
field

}

This is my response class.这是我的回应 class。 I want to send it by assigning the "Payload" variables in the response response object of the request.我想通过在请求的响应响应 object 中分配“有效负载”变量来发送它。 I couldn't figure out how to do.我不知道该怎么做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM