Unity Newtonsoft.Json的使用

26 篇文章 0 订阅

https://github.com/JamesNK/Newtonsoft.Json

安装

下载后选择相应的dll (我选的是2.0的)
放入Plugins 注意勾选对应的平台 (pc 选 standard x86 x86_64)

使用

转换model类 注意加上序列化属性
https://json2csharp.com/

[System.Serializable]
public class Apple
{
    public int id;
    public string type;
    public string name;

    public static Apple CreateFromJSON(string jsonString)
    {
        return JsonConvert.DeserializeObject<Apple>(jsonString);
    }

    // Given JSON input:
    // {"name":"Dr Charles","lives":3,"health":0.8}
    // this example will return a PlayerInfo object with
    // name == "Dr Charles", lives == 3, and health == 0.8f.
}

另附上一个Unity http的方便调用 (由于迭代器不能有ref out,所以用回调代替)

public class HttpClient : Singleton<HttpClient>
{

    /// <summary>
    /// 发送一个get请求
    /// </summary>
    /// <param name="uri"></param>
    /// <param name="action">返回结果</param>
    public void Get(string uri, Action<string> action)
    {
        GameManager.Instance.StartCoroutine(GetRequest(uri, action));
    }


    IEnumerator GetRequest(string uri, Action<string> action)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {

            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string[] pages = uri.Split('/');
            int page = pages.Length - 1;

            if (webRequest.isNetworkError)
            {
                Debug.Log(pages[page] + ": Error: " + webRequest.error);
            }
            else
            {
                var r = webRequest.downloadHandler.text;
                action.Invoke(r);

                //Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
                //Debug.Log(r);
            }
        }
    }
}

…Operation is not supported on this platform

Unity 2.0 切换到4.0就好,原因不明
github问题

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值