0评论

Unity 加载UTF-8 *.Json文件,调用JsonMapper.ToObject异常

文章来自CSDN博客 2018-08-09 37浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏开发行业精英群711501594

*.Json文件使用UTF-8文件不保存格式的话被LitJson中的JsonMapper.ToObject调用报异常:
JsonException:Invalidcharacter'?'ininputstring
LitJson.Lexer.NextToken()
LitJson.JsonReader.ReadToken()
LitJson.JsonReader.Read()
LitJson.JsonMapper.ReadValue(LitJson.WrapperFactoryfactory,LitJson.JsonReaderreader)
LitJson.JsonMapper.ToWrapper(LitJson.WrapperFactoryfactory,System.Stringjson)
LitJson.JsonMapper.ToObject(System.Stringjson)

有用UTF-8保存文件有4个无用字节i.e.
using UnityEngine;
using System.Collections;
using LitJson;
using System.Text;
public class GetVersion : MonoBehaviour {
    string CallFun = "";
    string filepath = "";
    private string _tipMessage = "";
    [SerializeField]
    private UISprite _loginBt;
    private Color _color=new Color(1,1,1,0.5f);
    void Start () {
        InitWWWJson("file://"+Application.dataPath + "/StreamingAssets/MusesMobileAppVersion.json", "");
    }
    public void InitWWWJson(string Path, string CallFun)
    {
        this.CallFun = CallFun;
        filepath = Path;
        WWW www = new WWW(filepath);
        StartCoroutine(LinkNetWork(www));
    }
    IEnumerator LinkNetWork(WWW www)
    {
        yield return www;
        if (www.error == null)
        {
            //ReadJson(www.text);直接使用抛异常
            string jsonData = System.Text.Encoding.UTF8.GetString(www.bytes, 3, www.bytes.Length - 3);  // Skip thr first 3 bytes (i.e. the UTF8 BOM)
            ReadJson(jsonData);
        }
    }
    private void ReadJson(string versionMessage)
    {
        Debug.Log( versionMessage);
        JsonData _json = JsonMapper.ToObject(versionMessage)["Diet"];
        string version= _json["version"].ToString();
        Debug.Log("版本号" + version);
        Debug.Log("name:" +  _json["name"].ToString());
        if (version != Application.version)
        {
            _tipMessage = _json["msg"].ToString();
            Messenger.Broadcast<string>("MessageBoxError", _tipMessage);
            if (_json["enabled"].ToString() != "true")
            {
                _loginBt.color = _color;
                _loginBt.transform.GetComponent<BoxCollider>().enabled = false;
            }
        }
    }
}

JSON文件
{
    "Diet": {
        "name": "91小二",
        "version": "1.1.2",
	"enabled":"true",
	"msg":"检测到新版本,请更新",
        "updateTime": "20160628"
    }
}
这个是一个简单的检测版本是否需要更新并提升,把*.json放到服务器上就可以了  
来自:https://blog.csdn.net/he_wen_jian/article/details/51781373