ToDictionary() public method

public ToDictionary ( ) : string>.Dictionary
return string>.Dictionary
Esempio n. 1
0
    /// <summary>
    /// 获取授权用户信息
    /// </summary>
    /// <param name="token"></param>
    /// <param name="openId"></param>
    private void GetAuthUserInfoJosnMap(string token, string openId)
    {
        //获取用户个人信息(UnionID机制)
        string userinfourl = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                             token + "&openid=" + openId;

        UnityWebRequest wxuserinfoReq = UnityWebRequest.Get(userinfourl);

        wxuserinfoReq.SetRequestHeader("Content-Type", "application/json");
        wxuserinfoReq.Send();
        while (!wxuserinfoReq.isDone)
        {
        }
        string userInfoContent = wxuserinfoReq.downloadHandler.text.Trim();

        wxuserinfoReq.Dispose();

        var userInfojsonobj = new JSONObject(userInfoContent);

        AuthUserInfoMap.Clear();
        AuthUserInfoMap = userInfojsonobj.ToDictionary();

        //删除headimgurl中多余的反斜杠(\)
        string headurlstr;

        if (AuthUserInfoMap.TryGetValue("headimgurl", out headurlstr))
        {
            string headimgurl = headurlstr.Replace("\\", "");
            AuthUserInfoMap["headimgurl"] = headimgurl;
        }
    }
Esempio n. 2
0
    IEnumerator WaitForRequest(WWW www)
    {
        Debug.Log("WaitForRequest called!!!");

        //If www is null, return
        yield return(www);

        //Debug.Log ("we are receiving requests");
        if (www.error == null)
        {
            Debug.Log("WaitForRequest and no error:");
            string receivedText = www.text;
            Debug.Log("Received Command from Server: " + receivedText);
            JSONObject jsonReceived          = new JSONObject(receivedText);
            Dictionary <string, string> dict = jsonReceived.ToDictionary();
            CarControll.isTurningLeft  = float.Parse(dict["isTurningLeft"]);
            CarControll.isTurningRight = float.Parse(dict["isTurningRight"]);
            CarControll.isNotTurning   = float.Parse(dict["isKeepingStraight"]);
            CarControll.isAccelerating = float.Parse(dict["isAccelerating"]);
            Debug.Log("Commands arrived at Car: " + jsonReceived.ToString());


            //accessData(serializedList);
        }
    }
Esempio n. 3
0
    /// <summary>
    /// 获取微信登陆授权token
    /// </summary>
    /// <param name="authcode"></param>
    /// <param name="authtoken"></param>
    /// <param name="authopenid"></param>
    private void GetAuthToken(string authcode, out string authtoken, out string authopenid)
    {
        authtoken  = string.Empty;
        authopenid = string.Empty;

        //通过code获取access_token的接口
        string urltoken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + PayPlatformDefine.WXAPPID
                          + "&secret=" + PayPlatformDefine.WXAppSECRET
                          + "&code=" + authcode
                          + "&grant_type=authorization_code";

        UnityWebRequest wxtokenReq = UnityWebRequest.Get(urltoken);

        wxtokenReq.SetRequestHeader("Content-Type", "application/json");
        wxtokenReq.Send();
        while (!wxtokenReq.isDone)
        {
        }
        string TokenContent = wxtokenReq.downloadHandler.text.Trim();

        wxtokenReq.Dispose();


        var jsonobj = new JSONObject(TokenContent);
        Dictionary <string, string> tokenDic = jsonobj.ToDictionary();

        if (tokenDic.TryGetValue("access_token", out authtoken))
        {
            tokenDic.TryGetValue("openid", out authopenid);
            Debug.Log("Wechat Auth Access_token:" + authtoken + " Open:" + authopenid);
        }
    }
Esempio n. 4
0
    public Dictionary <string, string> ParseFrom(string rawdata)
    {
        JSONObject jsonObj = new JSONObject(rawdata);
        Dictionary <string, string> data = jsonObj.ToDictionary();

        return(data);
    }
Esempio n. 5
0
        //购买商品回调
        void OnBuyFailedItem(string sJason)
        {
            Utils.LogSys.Log("--------------AppStorePay callback 3-------------sJason:" + sJason);
            JSONObject arrStr = new JSONObject(sJason);
            Dictionary <string, string> _dic = arrStr.ToDictionary();

            if (_dic == null)
            {
                //Utils.LogSys.Log("--------------AppStorePay callback 4-------------");
            }
            string nsRlt        = "";////nRlt:0进行中 1成功 2失败 3重新提交 4排队中
            string nsIdentifier = "";
            string nsReceipt    = "";

            if (_dic.ContainsKey("nsRlt"))
            {
                nsRlt = _dic["nsRlt"];
            }
            if (_dic.ContainsKey("nsIdentifier"))
            {
                nsIdentifier = _dic["nsIdentifier"];
            }
            Utils.LogSys.Log("--------------AppStorePay callback 5-------------nsRlt:" + nsRlt + " ,nsIdentifier:" + nsIdentifier);

            BuyItem_AppStore_Callback(nsRlt, nsIdentifier, nsReceipt, "");
        }
Esempio n. 6
0
    /// <summary>
    /// lua 赋值回 c#
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>

    public void InitUserWithDict_JsonStr(string jsonStr, string sessionArg)
    {
        JSONObject json = new JSONObject(jsonStr);

        //Debug.Log("json  === " + json.ToString());
        InitUserWithDict(json.ToDictionary(), sessionArg);
    }
Esempio n. 7
0
    private void UpdateStatsList(JSONObject data)
    {
        usersStats.Clear();

        foreach (JSONObject item in data["results"].list)
        {
            string name = item["name"].ToString();

            JSONObject stats   = item["stats"];
            bool       isEmpty = stats.ToDictionary().Count == 0;

            string games = isEmpty ? "0" : stats["games"].ToString();
            string wins  = isEmpty ? "0" : stats["wins"].ToString();
            string top5  = isEmpty ? "0" : stats["top5"].ToString();
            string kills = isEmpty ? "0" : stats["kills"].ToString();

            usersStats.Add(new Stats(
                               name: name,
                               gamesCount: games,
                               winsCount: wins,
                               top5Count: top5,
                               totalKillsCount: kills
                               ));
        }

        statsHandler.FillTable(usersStats);
    }
Esempio n. 8
0
    public Dictionary<string, string> ParseFrom(string rawdata)
    {
        JSONObject jsonObj = new JSONObject(rawdata);
        Dictionary<string, string> data = jsonObj.ToDictionary();

        return data;
    }
Esempio n. 9
0
        private void ParseAccessToken(JSONObject parsed)
        {
            var dict = parsed.ToDictionary();

            foreach (KeyValuePair <string, string> kvp in dict)
            {
                if (kvp.Key == "access_token")
                {
                    _oAuth2.Token = kvp.Value;
                    PlayerPrefs.SetString("FitbitAccessToken", kvp.Value);
                }
                else if (kvp.Key == "expires_in")
                {
                    var num = 0;
                    Int32.TryParse(kvp.Value, out num);
                    _oAuth2.ExpiresIn = num;
                }
                else if (kvp.Key == "refresh_token")
                {
                    _oAuth2.RefreshToken = kvp.Value;
                    Debug.Log("REFRESH TOKEN: " + kvp.Value);
                    PlayerPrefs.SetString("FitbitRefreshToken", kvp.Value);
                    Debug.Log("Token We Just Store: " + PlayerPrefs.GetString("FitbitRefreshToken"));
                }
                else if (kvp.Key == "token_type")
                {
                    _oAuth2.TokenType = kvp.Value;
                    PlayerPrefs.SetString("FitbitTokenType", kvp.Value);
                }
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Runs in background clientReceiveThread; Listens for incomming data.
 /// </summary>
 private void ListenForData()
 {
     try {
         socketConnection = new TcpClient("192.168.1.202", 8888);
         Byte[] bytes = new Byte[1024];
         while (true)
         {
             // Get a stream object for reading
             using (NetworkStream stream = socketConnection.GetStream()) {
                 int length;
                 // Read incomming stream into byte arrary.
                 while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                 {
                     var incommingData = new byte[length];
                     Array.Copy(bytes, 0, incommingData, 0, length);
                     // Convert byte array to string message.
                     string serverMessage = Encoding.ASCII.GetString(incommingData);
                     Debug.Log("server message received as: " + serverMessage);
                     JSONObject received = new JSONObject(serverMessage);
                     manager.dataUpdate(received.ToDictionary());
                 }
             }
         }
     }
     catch (SocketException socketException) {
         Debug.Log("Socket exception: " + socketException);
     }
 }
Esempio n. 11
0
    public void UpdateUserWithDict_JsonStr(string jsonStr)
    {
        JSONObject json = new JSONObject(jsonStr);

        //Debug.Log("json  === " + json.ToString());

        UpdateUserWithDict(json.ToDictionary());
    }
 static void GetAchievements(JSONObject achievementObject, out Dictionary <string, bool> achievements)
 {
     achievements = new Dictionary <string, bool>();
     foreach (var kvp in achievementObject.ToDictionary())
     {
         achievements.Add(kvp.Key, bool.Parse(kvp.Value));
     }
 }
Esempio n. 13
0
    /* ------ Other ------ */
    public HttpResult UpdateUserinfoResult(WWW www)
    {
        HttpResult result = BaseResult(www);

        if (HttpResult.ResultType.Sucess == result.resultType)
        {
            JSONObject resultObj = (JSONObject)result.resultObject;
            EginUser.Instance.UpdateUserWithDict(resultObj.ToDictionary());
        }
        return(result);
    }
    public virtual void BuildJSONData(JSONObject _json)
    {
        var idObj = _json.GetField("id");

        if (idObj == null)
        {
            UnityEngine.Debug.Log("An id column is missing in your table");
        }

        var props    = GetType().GetProperties();
        var dic      = _json.ToDictionary();
        var dbFields = dic.Select(x => x.Key).ToList(); //list of fields of the table

        foreach (var dbItem in dic)
        {
            //check value first
            if (dbItem.Value == null || string.IsNullOrEmpty(dbItem.Value.ToString()))
            {
                continue;
            }

            //try getting the property corresponding to the db field
            var prop = props.FirstOrDefault(x => x.Name.ToLower() == dbItem.Key.ToLower());
            if (prop != null)
            {
                //We'll convert a la mano (.NET 3.5)
                var valueStr = dbItem.Value.ToString();
                if (prop.PropertyType == typeof(string))
                {
                    prop.SetValue(this, valueStr, null);
                }
                else if (prop.PropertyType == typeof(int))
                {
                    int i = -1;
                    int.TryParse(valueStr, out i);
                    prop.SetValue(this, i, null);
                }
                else if (prop.PropertyType == typeof(float))
                {
                    float i = -1;
                    float.TryParse(valueStr, out i);
                    prop.SetValue(this, i, null);
                }
                else if (prop.PropertyType == typeof(double))
                {
                    double i = -1;
                    double.TryParse(valueStr, out i);
                    prop.SetValue(this, i, null);
                }
            }
        }
    }
Esempio n. 15
0
    private void OnLoginSuccess(JSONObject data)
    {
        MoveToTheMainMenu();

        resultDictionary = data.ToDictionary();

        DataHub.Instance.SetStringValue(Keys.PlayerData.playerToken, resultDictionary[API_Keys.LoginAndRegistration.playerToken]);
        DataHub.Instance.SetStringValue(Keys.PlayerData.expiresAt, resultDictionary[API_Keys.LoginAndRegistration.expiresAt]);
        DataHub.Instance.SetStringValue(Keys.PlayerData.userId, resultDictionary[API_Keys.LoginAndRegistration.userId]);

        if (resultDictionary.ContainsKey(API_Keys.LoginAndRegistration.isAdmin))
        {
            DataHub.Instance.SetStringValue(Keys.PlayerData.isAdmin, resultDictionary[API_Keys.LoginAndRegistration.isAdmin]);
        }
    }
Esempio n. 16
0
    private void OnBoardData(JSONObject js)
    {
        UnityThread.Instance.RunOnMainThread.Enqueue(() =>
        {
            try
            {
                Debug.Log(js);
                boardData         = js.GetField("_BOARD_").str;
                string gameStatus = js.GetField("_STATUS_").str;

                if (gameStatus == "1")
                {
                    js.RemoveField(username);
                    js.RemoveField("_BOARD_");
                    js.RemoveField("_STATUS_");

                    JSONObject avatars = js.GetField("AVATARS");
                    avatars.RemoveField("AVATAR_ID_" + username);


                    Dictionary <string, string> dic = avatars.ToDictionary();
                    Dictionary <string, string> .KeyCollection keys = dic.Keys;

                    foreach (string key in keys)
                    {
                        op_username = key;
                        op_imagID   = js.GetField("AVATARS").GetField(op_username).str;
                    }

                    if (op_username != null && boardData != null && op_imagID != null)
                    {
                        PlayerPrefs.SetString("OpponentName", op_username.Substring(10));
                        PlayerPrefs.SetString("Board", boardData);
                        PlayerPrefs.SetInt("op_picID", Convert.ToInt32(op_imagID));
                        Debug.Log("-------------Start GAME---------");
                        SceneManager.LoadScene(3);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Main Menu OnBoardData : " + e);
            }
        });
    }
Esempio n. 17
0
    /// <summary>
    /// 接收
    /// 获取用户信息, 返回数据的处理
    /// </summary>
    /// <param name="result"></param>
    public static void Receive_get_ccount(JSONObject result)
    {
        string session = "";
        //if (www.responseHeaders.ContainsKey("SET-COOKIE"))
        //{
        //    session = www.responseHeaders["SET-COOKIE"];
        //}
        //Dictionary<string, string> resultDict = ((JSONObject)result.resultObject).ToDictionary();
        //对socket协议中 字段 的不同进行修正
        Dictionary <string, string> resultDict = result.ToDictionary();

        if (!resultDict.ContainsKey("id"))
        {
            resultDict["id"] = resultDict["userid"];
        }
        if (!resultDict.ContainsKey("exp"))
        {
            resultDict["exp"] = resultDict["exp_value"];
        }
        if (!resultDict.ContainsKey("next_exp"))
        {
            resultDict["next_exp"] = resultDict["exp_value"];
        }
        if (!resultDict.ContainsKey("avatar_img"))
        {
            resultDict["avatar_img"] = "";
        }
        if (!resultDict.ContainsKey("agent"))
        {
            resultDict["agent"] = "";
        }
        if (!resultDict.ContainsKey("weak"))
        {
            resultDict["weak"] = "0";
        }
        if (!resultDict.ContainsKey("gold_money"))
        {
            resultDict["gold_money"] = "0";
        }

        //处理登录返回信息
        EginUser.Instance.InitUserWithDict(resultDict, session);
        EginUser.Instance.isGuest = false;
    }
Esempio n. 18
0
        public static string LoadConfig(string file, out Dictionary <string, string> config)
        {
            config = null;
            if (string.IsNullOrEmpty(file))
            {
                return("LoadConfig - filename is empty");
            }
            else
            {
                try
                {
#if UNITY_ENGINE || UNITY_5_3_OR_NEWER
                    TextAsset txt = ResManager.LoadResDeep(file, typeof(TextAsset)) as TextAsset;
                    if (txt == null)
                    {
                        return("LoadConfig - cannot load file: " + file);
                    }
                    else
                    {
                        JSONObject json = new JSONObject(txt.text);
                        config = json.ToDictionary();
                        return(null);
                    }
#else
                    var text = LoadText(file);
                    if (string.IsNullOrEmpty(text))
                    {
                        return("LoadConfig - cannot load file: " + file);
                    }
                    else
                    {
                        JSONObject json = new JSONObject(text);
                        config = json.ToDictionary();
                        return(null);
                    }
#endif
                }
                catch (Exception e)
                {
                    return(e.ToString());
                }
            }
        }
Esempio n. 19
0
  public IEnumerator PopulateBookshelf() {
    WWW curl = new WWW("https://rehgehstoy.firebaseio.com/books.json");

    yield return curl;

    Debug.Log(curl.text);
    if (!string.IsNullOrEmpty(curl.error)) {
      this.errorText.text = curl.error;
    } else {
      JSONObject jso = new JSONObject(curl.text);
      Dictionary<string, string> diccy = jso.ToDictionary();
      foreach (ShelfBook book in GameObject.FindObjectsOfType<ShelfBook>()) {
        if (diccy.ContainsKey(book.gameObject.name)) {
          book.bookText = Regex.Replace(diccy[book.gameObject.name], "%0D%0A", "\n");
        }
        book.GetComponent<Button>().interactable = true;
      }
    }
  }
Esempio n. 20
0
    public void VerifyReceipt(string receiptstr)
    {
        try
        {
            byte[] postBytes = Encoding.UTF8.GetBytes(receiptstr);

            //正式地址
            //var req = HttpWebRequest.Create("https://buy.itunes.apple.com/verifyReceipt");
            //测试地址
            var req = HttpWebRequest.Create("https://sandbox.itunes.apple.com/verifyReceipt");
            req.Method        = "POST";
            req.ContentType   = "application/json";
            req.ContentLength = postBytes.Length;

            using (var stream = req.GetRequestStream())
            {
                stream.Write(postBytes, 0, postBytes.Length);
                stream.Flush();
            }

            var    sendResp     = req.GetResponse();
            string sendRespText = "";
            using (var streamReader = new System.IO.StreamReader(sendResp.GetResponseStream()))
            {
                sendRespText = streamReader.ReadToEnd().Trim();
            }

            var jsonobj = new JSONObject(sendRespText);
            Dictionary <string, string> result = jsonobj.ToDictionary();

            Debug.Log("receipt return data:" + sendRespText);

            foreach (var a in result)
            {
                Debug.Log(a.Key + ":" + a.Value);
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log("Exception: " + ex.Message.ToString());
        }
    }
Esempio n. 21
0
    //Fills myDictionary with all JSON files
    void FillDictionary()
    {
        myDictionary = new Dictionary <string, string>();

        string fileContents;
        Dictionary <string, string> auxDic;

        foreach (var jsonFile in jsonFiles)
        {
            fileContents = jsonFile.text;

            JSONObject jsonObj = JSONObject.Create(fileContents);

            auxDic = jsonObj.ToDictionary();

            foreach (var entry in auxDic)
            {
                myDictionary.Add(entry.Key, entry.Value);
            }
        }
    }
Esempio n. 22
0
 private void AddLanguage()
 {
     try
     {
         Entries = new Dictionary <string, string>(_text.ToDictionary());
     }
     catch (Exception e)
     {
         if (e is ArgumentException)
         {
             var duplicates = _text.keys.GroupBy(x => x)
                              .Where(group => group.Count() > 1)
                              .Select(group => group.Key);
             foreach (var duplicate in duplicates)
             {
                 _logger.PrintError("Dubplcate key \"{0}\" in the file \"{1}!\"\nValue: {2}", duplicate, Filename, _text[duplicate]);
             }
         }
         throw GenerateException("Can't load language \"{0}\"", e, Filename);
     }
 }
Esempio n. 23
0
    /// <summary>
    /// 购买成功处理
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        Debug.Log("Purchase OK: " + args.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + args.purchasedProduct.receipt);


        var jsonobj = new JSONObject(args.purchasedProduct.receipt);
        Dictionary <string, string> result = jsonobj.ToDictionary();
        string receiptPayload = result["Payload"];
        //Debug.Log("xxxxx jsonreceipt payload:" + receiptPayload);

        //以下为测试验证,正确流程是把json发送给服务器,服务器拿这个去apple itune验证
        string json = "{\"receipt-data\":\"" + receiptPayload + "\"}";

        //VerifyReceipt(json);

        Player.SendBuyReceiptToServer(PayPlatform.Apple, json);
        //购买流程已结束,等待服务器验证结果
        Player.BuyEnd();

        bPurchaseInProgress = false;
        return(PurchaseProcessingResult.Complete);
    }
Esempio n. 24
0
    public Node CreateNodeModel(string pathSeparator, string path, JSONObject folderOrFile, Dictionary <BuildingProperty, MetricMapping> mappings)
    {
        if (folderOrFile.GetField("type").str.Equals("Folder"))
        {
            List <Node> list = new List <Node> ();
            foreach (JSONObject child in folderOrFile.GetField("children").list)
            {
                list.Add(CreateNodeModel(pathSeparator, path + ((path.Length != 0) ? pathSeparator : "") + folderOrFile.GetField("name").str, child, mappings));
            }
            return(new StreetNode(list.ToArray()));
        }
        else if (folderOrFile.GetField("type").str.Equals("File"))
        {
            JSONObject   attribs  = folderOrFile.GetField("attributes");
            BuildingNode building = new BuildingNode();
            building.pathName = path;
            building.name     = folderOrFile.GetField("name").str;
            building.heightMappedAttribute = mappings[BuildingProperty.Height].metricName;
            building.groundMappedAttribute = mappings[BuildingProperty.Width].metricName;
            building.colorMappedAttribute  = mappings[BuildingProperty.Red].metricName;

            building.height     = mappings [BuildingProperty.Height].Apply(attribs);
            building.groundSize = mappings [BuildingProperty.Width].Apply(attribs);

            building.color = new Vector3(
                mappings[BuildingProperty.Red].Apply(attribs), mappings[BuildingProperty.Green].Apply(attribs), mappings[BuildingProperty.Blue].Apply(attribs)
                );

            foreach (KeyValuePair <string, string> attrib in attribs.ToDictionary())
            {
                building.allAttributes[attrib.Key] = attrib.Value;
            }

            return(building);
        }
        return(null);
    }
Esempio n. 25
0
        //购买商品回调
        void OnBuyCompleteItem(string sJason)
        {
            //Utils.LogSys.Log("--------------AppStorePay callback 0-------------sJason:" + sJason);
            JSONObject arrStr = new JSONObject(sJason);
            Dictionary <string, string> _dic = arrStr.ToDictionary();

            if (_dic == null)
            {
                Utils.LogSys.Log("--------------AppStorePay callback 1-------------");
            }
            string nsRlt         = "";////nRlt:0进行中 1成功 2失败 3重新提交 4排队中
            string nsIdentifier  = "";
            string nsReceipt     = "";
            string nsTransaction = "";

            if (_dic.ContainsKey("nsRlt"))
            {
                nsRlt = _dic["nsRlt"];
            }
            if (_dic.ContainsKey("nsIdentifier"))
            {
                nsIdentifier = _dic["nsIdentifier"];
            }
            if (_dic.ContainsKey("nsReceipt"))
            {
                nsReceipt = _dic["nsReceipt"];
            }

            if (_dic.ContainsKey("nsTransactionNum"))
            {
                nsTransaction = _dic["nsTransactionNum"];
            }
            ShopData.IOSPay_AddOrderNum(nsTransaction, nsReceipt, nsIdentifier);
            Utils.LogSys.Log("--------------AppStorePay callback 2-------------nsRlt:" + nsRlt + " ,nsIdentifier:" + nsIdentifier + " , nsReceipt:" + nsReceipt);

            BuyItem_AppStore_Callback(nsRlt, nsIdentifier, nsReceipt, nsTransaction);
        }
Esempio n. 26
0
	public void LoadConfiguration()
	{
		JSONObject configJSON = new JSONObject(loadConfigFile());
		m_ConfigData = configJSON.ToDictionary();
	}
Esempio n. 27
0
        private void ParseAccessToken(JSONObject parsed)
        {
            var dict = parsed.ToDictionary();
            foreach (KeyValuePair<string, string> kvp in dict)
            {
                if (kvp.Key == "access_token")
                {
                    _oAuth2.Token = kvp.Value;
                    PlayerPrefs.SetString("FitbitAccessToken", kvp.Value);
                }
                else if (kvp.Key == "expires_in")
                {
                    var num = 0;
                    Int32.TryParse(kvp.Value, out num);
                    _oAuth2.ExpiresIn = num;

                }
                else if (kvp.Key == "refresh_token")
                {
                    _oAuth2.RefreshToken = kvp.Value;
                    Debug.Log("REFRESH TOKEN: " + kvp.Value);
                    PlayerPrefs.SetString("FitbitRefreshToken", kvp.Value);
                    Debug.Log("Token We Just Store: " + PlayerPrefs.GetString("FitbitRefreshToken"));
                }
                else if (kvp.Key == "token_type")
                {
                    _oAuth2.TokenType = kvp.Value;
                    PlayerPrefs.SetString("FitbitTokenType", kvp.Value);
                }
            }
        }
Esempio n. 28
0
 // 데이터 처리
 private Dictionary<string, string> ProcessData(string jsonrawData)
 {
     JSONObject t = new JSONObject(jsonrawData);
     return t.ToDictionary();
 }
Esempio n. 29
0
    public IEnumerator AddFaceToListReq(byte[] imageBytes, Face[] faces)
    {
        String url             = "https://content.dropboxapi.com/2/files/upload";
        String path            = "";
        String mostSimilarFace = "";
        var    www             = new UnityWebRequest(url, "POST");

        www.uploadHandler   = (UploadHandler) new UploadHandlerRaw(imageBytes);
        www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        www.SetRequestHeader("Authorization", "Bearer ypTkH5v4AOAAAAAAAAABd_ST-h2I2UmZpwzxdXIWnYZW9N8-Njuuqsqj6RiUyZwL");
        www.SetRequestHeader("Dropbox-API-Arg", "{\"path\": \"/pic.jpg\",\"mode\": \"add\",\"autorename\": true}");
        www.SetRequestHeader("Content-Type", "application/octet-stream");

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log("error: " + www.error);
        }
        else
        {
            //Dictionary<string, string> json = JsonUtility.FromJson(www.downloadHandler.text, );
            JSONObject json = new JSONObject(www.downloadHandler.text);
            Dictionary <string, string> data = json.ToDictionary();
            path = "/" + data["name"];
            Debug.Log(path);

            String jsonString = "{\"path\": " + "\"" + path + "\"}";
            byte[] bytes      = Encoding.UTF8.GetBytes(jsonString);



            UnityWebRequest wwww = new UnityWebRequest("https://api.dropboxapi.com/2/files/get_temporary_link", "POST");
            wwww.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bytes);
            wwww.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            wwww.SetRequestHeader("Authorization", "Bearer ypTkH5v4AOAAAAAAAAABd_ST-h2I2UmZpwzxdXIWnYZW9N8-Njuuqsqj6RiUyZwL");
            wwww.SetRequestHeader("Content-Type", "application/json");

            yield return(wwww.SendWebRequest());

            if (wwww.isNetworkError || wwww.isHttpError)
            {
                Debug.Log("error: " + wwww.error);
            }
            else
            {
                Face   face   = faces[0];
                String output = wwww.downloadHandler.text;
                Debug.Log(output);


                String findSimilarUrl  = FaceServiceHost + "/findsimilars";
                String paramsJson      = "{\"faceId\": \"" + face.faceId + "\" , \"faceListId\": \"" + faceListID + "\" , \"maxNumOfCandidates\": " + "1, \"mode\": \"matchPerson\"}";
                byte[] paramsJsonBytes = Encoding.UTF8.GetBytes(paramsJson);

                UnityWebRequest findSimilarReq = new UnityWebRequest(findSimilarUrl, "POST");
                findSimilarReq.uploadHandler   = (UploadHandler) new UploadHandlerRaw(paramsJsonBytes);
                findSimilarReq.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                findSimilarReq.SetRequestHeader("Ocp-Apim-Subscription-Key", faceSubscriptionKey);
                findSimilarReq.SetRequestHeader("Content-Type", "application/json");
                yield return(findSimilarReq.SendWebRequest());

                if (findSimilarReq.isNetworkError || findSimilarReq.isHttpError)
                {
                    Debug.Log("error: " + findSimilarReq.error);
                }
                else
                {
                    try
                    {
                        SimilarFaceCollection similarFace = JsonUtility.FromJson <SimilarFaceCollection>("{\"faces\": " + findSimilarReq.downloadHandler.text + "}");
                        mostSimilarFace = similarFace.faces[0].persistedFaceId;
                    }
                    catch (Exception e)
                    {
                        Debug.Log("Exception caught.");
                    }
                }


                JSONObject jSONObject = new JSONObject(output);
                Dictionary <string, string> picData = jSONObject.ToDictionary();
                String link = picData["link"];
                Debug.Log(link);

                FaceRectangle faceRect = face.faceRectangle;

                String addFaceToListUrl = FaceServiceHost + "/facelists/" + faceListID + "/persistedfaces?userData=" + link + "&targetFace=" + faceRect.left + "," + faceRect.top + "," + faceRect.width + "," + faceRect.height;

                String          urlJsonString = "{\"url\": \"" + link + "\"}";
                byte[]          urlJsonBytes  = Encoding.UTF8.GetBytes(urlJsonString);
                UnityWebRequest faceListAdd   = new UnityWebRequest(addFaceToListUrl, "POST");
                faceListAdd.uploadHandler   = (UploadHandler) new UploadHandlerRaw(urlJsonBytes);
                faceListAdd.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                faceListAdd.SetRequestHeader("Ocp-Apim-Subscription-Key", faceSubscriptionKey);
                faceListAdd.SetRequestHeader("Content-Type", "application/json");
                yield return(faceListAdd.SendWebRequest());

                if (faceListAdd.isNetworkError || faceListAdd.isHttpError)
                {
                    Debug.Log("error: " + faceListAdd.error);
                }
                else
                {
                    Debug.Log(faceListAdd.downloadHandler.text);
                }
            }
        }

        String          getFaceListUrl = FaceServiceHost + "/facelists/" + faceListID;
        UnityWebRequest getList        = UnityWebRequest.Get(getFaceListUrl);

        PersistedFace[] persistedFaces = null;
        getList.SetRequestHeader("ocp-apim-subscription-key", faceSubscriptionKey);
        yield return(getList.SendWebRequest());

        if (getList.isNetworkError || getList.isHttpError)
        {
            Debug.Log("error: " + getList.error);
        }
        else
        {
            PersistedFaceCollection persistedFaceColl = JsonUtility.FromJson <PersistedFaceCollection>(getList.downloadHandler.text);
            persistedFaces = persistedFaceColl.persistedFaces;
            Debug.Log(persistedFaces[0].persistedFaceId);
        }

        String mostSimilarFaceUrl = "";

        foreach (PersistedFace face in persistedFaces)
        {
            if (face.persistedFaceId.Equals(mostSimilarFace))
            {
                mostSimilarFaceUrl = face.userData;
                Debug.Log(mostSimilarFaceUrl);
            }
        }
    }
Esempio n. 30
0
        /// <summary>
        /// 解析xml数据
        /// </summary>
        /// <param name="Config">xml文件字符串</param>
        public void ParseXML(string Config)
        {
            JSONObject arrStr = new JSONObject(Config);

            if (arrStr == null || arrStr.Count == 0)
            {
                Utils.LogSys.LogError("-------------localNotification Config is null : -------------");
                return;
            }
            List <JSONObject> myList = arrStr[0].list;

            if (myList == null || myList.Count == 0)
            {
                return;
                //Utils.LogSys.Log("--------------AppStorePay callback 1-------------");
            }
            System.DateTime nowDay   = System.DateTime.Now;
            System.DateTime tempWeek = System.DateTime.Now;

            for (int i = 0; i < myList.Count; i++)
            {
                JSONObject item_temp             = myList[i];
                Dictionary <string, string> item = item_temp.ToDictionary();
                string loopType = "day";
                if (item.ContainsKey("open"))
                {
                    if (item["open"].ToLower() != "true")
                    {
                        continue;
                    }
                }
                int key = 0;
                if (item.ContainsKey("id"))
                {
                    int.TryParse(item["id"], out key);
                }
                string sTitle = "";
                if (item.ContainsKey("title"))
                {
                    sTitle = item["title"];
                }
                string sMessage = "";
                if (item.ContainsKey("text"))
                {
                    sMessage = item["text"];
                }

                string sWeek   = "-1";
                int    weekDay = 1;
                if (item.ContainsKey("week"))
                {
                    sWeek = item["week"].ToLower();
                    if (sWeek != "-1")
                    {
                        loopType = "week";
                        int.TryParse(item["week"], out weekDay);
                        weekDay = Mathf.Clamp(weekDay, 1, 7);
                    }
                }

                int yy = 0;
                if (item.ContainsKey("yy"))
                {
                    int.TryParse(item["yy"], out yy);
                }
                int mm = 0;
                if (item.ContainsKey("mm"))
                {
                    int.TryParse(item["mm"], out mm);
                }
                int dd = 0;
                if (item.ContainsKey("dd"))
                {
                    int.TryParse(item["dd"], out dd);
                }
                int hour = 0;
                if (item.ContainsKey("hour"))
                {
                    int.TryParse(item["hour"], out hour);
                }
                int min = 0;
                if (item.ContainsKey("minute"))
                {
                    int.TryParse(item["minute"], out min);
                }
                int second = 0;

                yy   = (yy == -1) ? nowDay.Year : yy;
                mm   = (mm == -1) ? nowDay.Month : mm;
                dd   = (dd == -1) ? nowDay.Day : dd;
                hour = (hour == -1) ? nowDay.Hour : hour;
                min  = (min == -1) ? nowDay.Minute : min;
                System.DateTime newDate = new System.DateTime(yy, mm, dd, hour, min, second);
                if (loopType == "week")
                {
                    int nowWeek = (int)nowDay.DayOfWeek - 1;//周天是0,周一是1......
                    if (nowWeek == -1)
                    {
                        nowWeek = 6;
                    }
                    nowWeek += 1;//要转成周天是7, 周一是1, 周二是2
                    int offset = weekDay - nowWeek;
                    offset = offset < 0 ? offset + 7 : offset;
                    if (offset > 0)
                    {
                        newDate = newDate.AddDays(offset);
                    }
                }
                else
                {
                    if (nowDay.CompareTo(newDate) >= 0) //nowDay >= newDate
                    {
                        newDate = newDate.AddDays(1);   //如果现在时间比闹钟时大,则取第二天时间
                        //newDate = new System.DateTime(nowDay.Year, nowDay.Month, nowDay.Day, hour, min, second);
                        Utils.LogSys.Log("--------------add notification next:" + newDate.ToString() + "-------------");
                    }
                    else
                    {
                        Utils.LogSys.Log("--------------add notification :" + newDate.ToString() + "-------------");
                    }
                }
                localNotification.AddNotificationMessage(sTitle, sMessage, newDate, loopType, key);
            }
        }
Esempio n. 31
0
    public Dictionary <string, string> PicJson(string json)
    {
        var jsonObj = new JSONObject(WWW.UnEscapeURL(json));

        return(jsonObj.ToDictionary());
    }
 public Dictionary<string, string> getResponse()
 {
     JSONObject json = new JSONObject(www.text);
         Debug.Log("Response: " + www.text);
         return json.ToDictionary();
 }
    //---------------------------------------------------------------------
    //-------------------------  PUBLIC METHODS  --------------------------
    //---------------------------------------------------------------------

    // Use this to do a POST and create a session
    public IEnumerator LOGINUser(string email, string password)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        // First thing first - I need to do some cleanup of the email string
        // And I need to store those informations for other calls
        login_email = CleanInput(email);
        login_password = password;

        JSONObject nested_fields = new JSONObject(JSONObject.Type.OBJECT);
        nested_fields.AddField("email", login_email);
        nested_fields.AddField("password", login_password);
        JSONObject root_field = new JSONObject(JSONObject.Type.OBJECT);
        root_field.AddField("user", nested_fields);

        string encodedString = root_field.ToString();

        string result = "";

        while (!allProper && retryCount > 0)
        {
            // the actual call, in a try catch
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    result = client.UploadString(login_url, "POST", encodedString);
                }
                allProper = true;
            }
            catch (WebException ex)
            {
                retryCount--;

                if (retryCount == 0)
                {
                    Debug.Log("TESTexception: " + ex);
                    var response = ex.Response as HttpWebResponse;
                    errorHandler = RestError.GenericLoginError;

                    if (response != null)
                    {
                        Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                        switch ((int)response.StatusCode)
                        {

                            case 400:
                                errorHandler = RestError.WrongMail;
                                break;
                            case 401:
                                errorHandler = RestError.WrongPassword;
                                break;
                            case 500:
                                errorHandler = RestError.ServerError;
                                break;
                            default:
                                break;
                        }
                        break;
                    }
                }
            }
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
            JSONObject j = new JSONObject(result);
            // this won't work everytime
            Dictionary<string, string> decoded_response = j.ToDictionary();
            token = decoded_response["token"];
            logged_user_complete_name = decoded_response["complete_name"];
            logged_user_id = decoded_response["id"];


            int sessionCounter = int.Parse(decoded_response["sessions_counter"]);

            if (sessionCounter > 0)
            {
                sessionsHandler = RestSession.MultipleActive;
            }
        }
    }