1. 程式人生 > >txt格式文字解析(注意:編碼格式必須是UTF-8)

txt格式文字解析(注意:編碼格式必須是UTF-8)

資料內容:

{ "code": 200, "message": "操作成功", "data":{         "carid":"1"         "action0":"1"         "action1":"1"         "action2":"0"         "action3":"1"         "action4":"0"         "action5":"1"         "action6":"0" }}

程式碼部分

    #region txt格式文字解析(編碼格式必須是UTF-8)

    public Text console;
    public string message;
    public string tempStr;

    Dictionary<string, string> strDic = new Dictionary<string, string>();
    void Start()
    {
        TextAsset txt = Resources.Load("data") as TextAsset;
        string[] strs = txt.text.Split('\n', '\t', '"', '{', '}', ' ','\v');
        //strs = message.Split('\n');
        foreach (string str in strs)
        {
            string[] s = str.Split(',', ':');
            //string[] s = str.Split(new string[] { ",", ":" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < s.Length; i++)
            {
                tempStr = console.text += s[i];
            }
        }

        string[] ss = tempStr.Split(new string[] {"carid", "action0", "action1", "action2", "action3", "action4", "action5", "action6"}, StringSplitOptions.RemoveEmptyEntries);

        for(int i = 1; i <= 8; i++)
        {
            if(i == 1)
            {
                strDic.Add("carid", ss[i]);
            }
            else
            {
                strDic.Add("action" + (i - 1), ss[i]);
            }
        }

        foreach (KeyValuePair<string, string> pair in strDic)
        {
            print(pair.Key + " : " + pair.Value);
        }
    }

    private bool intValue(string intStr)
    {
        try
        {
            int varInt = Convert.ToInt32(intStr);
            return true;
        }
        catch
        {
            string varStr = Convert.ToString(intStr);
            return false;
        }
    }
    #endregion