【问题标题】:How to get JSON objects in Unity using REST如何使用 REST 在 Unity 中获取 JSON 对象
【发布时间】:2019-09-18 04:27:28
【问题描述】:

我已经进行了一段时间的故障排除,但没有成功为我的统一应用程序获得正确的响应。从客户端到服务器的登录帖子是成功的,只是我期望的响应不是我团结的正确响应。请检查我下面的代码。

这是模型类

using System;
using System.Collections;
using System.Collections.Generic;
namespace Models
{
    [Serializable]
    public class Post
    {
        public string identifier;
        public string password;
        public string jwt;
        public string user;
        public override string ToString(){
            return UnityEngine.JsonUtility.ToJson (this, true);
        }
    }
}

这是我的发帖请求

using UnityEngine;
using UnityEditor;
using Models;
using Proyecto26;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine.UI;

using SimpleJSON;

public class MainScript : MonoBehaviour {

    private readonly string basePath = "http://localhost:1337";
    private RequestHelper currentRequest;
    public InputField username;
    public InputField password;


    private void LogMessage(string title, string message) {
#if UNITY_EDITOR
        EditorUtility.DisplayDialog (title, message, "Ok");
#else
        Debug.Log(message);
#endif
public void Post(){

        Debug.Log(username.text);
        Debug.Log(password.text);
        currentRequest = new RequestHelper {
            Uri = basePath + "/auth/local",
            Body = new Post {
                 identifier ="gofor+bs@gmail.com",
                 password ="12345678"
            }
        };
        RestClient.Post<Post>(currentRequest)
        .Then(
            res => {
                EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(res, true), "Ok");
                Debug.Log(JsonUtility.ToJson(res, true));
            }
            // this.LogMessage("Success",  )
            )
        .Catch(err => this.LogMessage("Error", err.Message));
    }
    }

这是 POSTMAN 在成功验证/登录后的响应。

{
    "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDgxOWI5ZWVmYWY3ZDE0MjRhMGNlM2UiLCJpZCI6IjVkODE5YjllZWZhZjdkMTQyNGEwY2UzZSIsImlhdCI6MTU2ODc3NTYzMywiZXhwIjoxNTcxMzY3NjMzfQ.-v33TvKW2pLuLU-w596bzXAamC0Wecpfrv3pOPsB_bI",
    "user": {
        "_id": "5d819b9eefaf7d1424a0ce3e",
        "confirmed": true,
        "blocked": false,
        "email": "gofor+bs@gmail.com",
        "username": "user1",
        "provider": "local",
        "__v": 0,
        "id": "5d819b9eefaf7d1424a0ce3e",
        "role": {
            "_id": "5d8040be9a4f6d25281e8097",
            "name": "Authenticated",
            "description": "Default role given to authenticated user.",
            "type": "authenticated",
            "__v": 0
        }
    }
}

这是我收到的回复

用户对象是我需要的,但这里它是空的。

{
    "identifier": "",
    "password": "",
    "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDgxOWI5ZWVmYWY3ZDE0MjRhMGNlM2UiLCJpZCI6IjVkODE5YjllZWZhZjdkMTQyNGEwY2UzZSIsImlhdCI6MTU2ODc3ODY1MCwiZXhwIjoxNTcxMzcwNjUwfQ.vCC_EwyH5iAUT6y83PuF92F7Xok4cGhdlkSU7Y0kYqE",
    "user": ""
}

我应该如何获取“用户”字符串/对象?我还是 C# 和 Unity 的新手,所以我需要一些专家建议来了解如何在这里做。我感谢你们的帮助。提前谢谢你。

【问题讨论】:

标签: c# json unity3d


【解决方案1】:

您的user 不是一个简单的string,而是一个复杂的类型,甚至还有一个子类型role

为了获得这些,您的 c# 数据结构必须完全镜像 JSON 结构。

最简单的开始方式:将您的 json 传递给 Json2CSharp

并稍微修改结果以使其与统一工作:

[Serializable]
public class Role
{
    public string _id;
    public string name;
    public string description;
    public string type;
    public int __v;
}

[Serializable]
public class User
{
    public string _id;
    public bool confirmed;
    public bool blocked;
    public string email;
    public string username;
    public string provider;
    public int __v;
    public string id;
    public Role role;
}

[Serializable]
public class Post
{
    // use NonSerialized to avoid these being printed to the json
    [System.NonSerialized] public string identifier;
    [System.NonSerialized] public string password;

    public string jwt;
    public User user;

    public override string ToString()
    {
        return UnityEngine.JsonUtility.ToJson (this, true);
    }
}

类名可以随意命名,因为 Json 不在乎。


还要注意,一般来说这是相当多余的

EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(res, true), "Ok");
Debug.Log(JsonUtility.ToJson(res, true));

如果只是显示 json,您可能更愿意使用 JSON.Net 而不是 Unity 的 JsonUtility 并且可以简单地执行 (source)

string jsonFormatted = JValue.Parse(res).ToString(Formatting.Indented);

EditorUtility.DisplayDialog("JSON", jsonFormatted, "Ok");
Debug.Log(jsonFormatted);

甚至根本不需要关心 c# 数据结构。

【讨论】:

  • 谢谢兄弟一切正常!但我还有另一个问题。如果在用户模型中有另一个字段是数组,我该如何处理?这就是我所做的。所以基本上我想在 {"kids": [{name:"kid1"}, {name:"kid2"}] } 中获取数组对象,我为它创建了另一个模型,但它不起作用。请在此处查看我的代码:repl.it/@Jerson_AndyAndy/CUserModel – andymyst
  • @andymyst 正如所说,c# 结构必须完全 镜像 JSON 结构,最重要的是匹配字段名称。在您的 JSON 中,Kid 类有一个字段 name ..(注意,这不是正确的 JSON!字段名称必须包含在 " 中,因此它应该是 {"kids": [{"name":"kid1"}, {"name":"kid2"}] })在您的 c# 代码中但是您只有 firstnamelastname 字段,但 name 没有字段
  • 感谢您的回复。实际上我是在 JSON2charp 上生成的。我已经在我给你的链接上更新了我的代码。此外,这里是我正在构建的 unity3d 应用程序的一个非常短的截屏视频,该应用程序在儿童数组 [link]screencast.com/t/ukg1amQpl 我非常需要帮助 :-( 这是我的第一个涉及 json 的 Unity 应用程序。谢谢你的回答兄弟!
  • 好吧 .. 它似乎与您的课程无关,但服务器或您从中获取此 JSON 的任何地方只是向您发送一个空数组。 (对于降价链接格式就像[label](url) btw ;))
  • 哈哈哈抱歉,这对我来说都是全新的 :-) 我会调查的。似乎对我连接的 api 有限制。再次感谢您的帮助:-)
猜你喜欢
  • 2014-07-11
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多