Add() public method

public Add ( JSON, obj ) : void
obj JSON,
return void
コード例 #1
0
ファイル: test.cs プロジェクト: gishowm/QualityAudit
        public static dynamic getJDBabyInfo(string goodsUrl)
        {
            JSON urlData = new JSON
            {
                { "shopid", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.店铺编号) },
                { "goodsid", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝编号) },
                { "shopName", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.店铺名称) },
                { "goodsprice", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝价格) },
                { "shopUrl", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.店铺链接) },
                { "babyName", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝名称) },
                { "brandName", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝品牌) },
                { "categoryName", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝分类) },
                { "marketTime", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.市时间) },
                { "appliesCrowd", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.适用人群) },
                { "appliesSeason", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.适用季节) },
                { "appliesPlace", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.适用场地) },
                { "appliesGender", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.适用性别) },
                { "appliesAge", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.适用年龄) },
                { "domesticEntrance", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.进口国产) },
                { "image", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝主图) },
                { "goodsShortName", Core.Tasks.JDTask.getInfoByUrlAndKey(goodsUrl, Core.Tasks.JDTask.Feilds.宝贝名称) },
            };

            urlData.Add("startprice", urlData.String("goodsprice"));
            urlData.Add("endprice", urlData.String("goodsprice"));
            return(urlData);
        }
コード例 #2
0
        private void SerAndDeserUnityStructs()
        {
            // Create some basic Unity structs
            Vector3    v3  = new Vector3(3f, 14f, 15f);
            Quaternion q   = new Quaternion(3f, 3f, 3f, 4f);
            Color32    c32 = new Color32(128, 255, 0, 192);
            Color      c   = new Color(0.5f, 1f, 0f, 0.75f);

            // Serialize them to JSON and store under one JSON object
            JSON jsonObject = new JSON();

            jsonObject.Add("v3", JSON.Serialize(v3));
            jsonObject.Add("q", JSON.Serialize(q));
            jsonObject.Add("c32", JSON.Serialize(c32));
            jsonObject.Add("c", JSON.Serialize(c));

            // Print out
            Debug.Log("Structs stored to JSON: " + jsonObject.CreateString());

            // Recreate (deserialize) structs from JSON
            Vector3    vector3recreated    = jsonObject.GetJSON("v3").Deserialize <Vector3>();
            Quaternion quaternionRecreated = jsonObject.GetJSON("q").Deserialize <Quaternion>();
            Color32    color32recreated    = jsonObject.GetJSON("c32").Deserialize <Color32>();
            Color      colorRecreated      = jsonObject.GetJSON("c").Deserialize <Color>();

            // Print out
            Debug.Log("Vector3 recreated: " + vector3recreated);
            Debug.Log("Quaternion recreated: " + quaternionRecreated);
            Debug.Log("Color32 recreated: " + color32recreated);
            Debug.Log("Color recreated: " + colorRecreated);
        }
コード例 #3
0
        protected override void BeginWriteObject()
        {
            m_Stack.Push(m_Current);
            JSON newObj = JSON.CreateObject();

            m_Current.Add(newObj);
            m_Current = newObj;
        }
コード例 #4
0
    public void Save()
    {
        JSON json = new JSON();

        json.Add(SaveLoadManagerWithVersion.VersionKey, SaveLoadManagerWithVersion.CurrentVersion);
        json.Add("inventory", playerInventory.value.GetSaveData());
        SaveLoadManagerWithVersion.Save(json, "PlayerInventory", 0);
    }
コード例 #5
0
    public JSON Save()
    {
        JSON data = new JSON();

        data.Add("name", name);
        data.Add("surname", surname);
        data.Add("nickName", nickName);
        return(data);
    }
コード例 #6
0
    public static JSON AsJson(this Color color)
    {
        JSON json = new JSON();

        json.Add("a", color.a);
        json.Add("r", color.r);
        json.Add("g", color.g);
        json.Add("b", color.b);
        return(json);
    }
コード例 #7
0
    // if isNewAttempt is false,  then look for current SelectedStudent and use that to replace the data/ add data to that object
    public bool SetPlayerActionsSelectedStudentData(string key, string value, bool isNewAttempt = false)
    {
        if (currentSecnarioMasterKey != "")
        {
            if (isNewAttempt)
            {
                if (key != null && key != "")
                {
                    if (key != "SelectionID" && key != "StudentName" && key != "TimeStamp")
                    {
                        Debug.LogAssertion("Key for New attepmt of Student Selection is not an expected key");
                        return(false);
                    }
                    currentStudentSelectedID = LogData.GetJSON(currentSecnarioMasterKey).GetJSON("PlayerActions").GetJArray("SelectedStudent").Length;
                    JSON StudentSelectedSubActionsObject = new JSON(); // inner object of Teacher Sub Action
                    StudentSelectedSubActionsObject.Add("SelectionID", currentStudentSelectedID);
                    StudentSelectedSubActionsObject.Add(key, value);
                    LogData.GetJSON(currentSecnarioMasterKey).GetJSON("PlayerActions").GetJArray("SelectedStudent").Add(StudentSelectedSubActionsObject);
                    //currentTASData.Add(TeacherSubActionsObject);
                    logDataUpdated = true;
                    return(true);
                }
                Debug.LogAssertion("Key for New attepmt of Student Selection is empty or null");
                return(false);
            }
            else
            {
                if (key != null && key != "")
                {
                    if (key != "SelectionID" && key != "StudentName" && key != "TimeStamp" && key != "Duration" && key != "Phase")
                    {
                        Debug.LogAssertion("Key for adidng or replaceing a part of exiting of Student Selection  is not an expected key");
                        return(false);
                    }

                    if (key == "Duration" && value == "00:00")
                    {
                        LogData.GetJSON(currentSecnarioMasterKey).GetJSON("PlayerActions").GetJArray("SelectedStudent").RemoveAt(currentStudentSelectedID);
                    }
                    else
                    {
                        LogData.GetJSON(currentSecnarioMasterKey).GetJSON("PlayerActions").GetJArray("SelectedStudent").GetJSON(currentStudentSelectedID).AddOrReplace(key, value);
                    }


                    logDataUpdated = true;
                    return(true);
                }
                Debug.LogAssertion("Key for adidng or replacning a part of exiting of Student Selection is empty or null");
                return(false);
            }
        }
        Debug.LogAssertion("Please use SetScenarioMasterLogObject with appropriate key to start logging this into the correct scenario");
        return(false);
    }
コード例 #8
0
        private void Test2()
        {
            // Create new JSON object from dictionary
            Dictionary <string, object> dict = new Dictionary <string, object>();

            dict.Add("one", 1);
            dict.Add("two", 2f);
            JSON jsonFromDict = new JSON(dict);

            // Create new JSON array from list
            List <string> list = new List <string>();

            list.Add("ABC");
            list.Add("XYZ");
            list.Add("ijk");
            JArray jArrayFromList = new JArray(list);

            // Create number that would be outside c# supported integers, by creating new JSON number from string
            JNumber bigInteger = new JNumber("184467440737095516150");

            // Add them all to one JSON
            JSON json = new JSON();

            json.Add("fromDict", jsonFromDict);
            json.Add("fromList", jArrayFromList);
            json.Add("bigInteger", bigInteger);

            // Print out in pretty form
            Debug.Log(json.CreateString(new CreateStringSettings()
            {
                HumanReadable = true
            }));

            /*
             *      Prints out:
             *      {
             *              "fromDict": {
             *                      "one": 1,
             *                      "two": 2.0
             *              },
             *              "fromList": [
             *                      "ABC",
             *                      "XYZ",
             *                      "ijk"
             *              ],
             *              "bigInteger": 184467440737095516150
             *      }
             */
        }
コード例 #9
0
    public static void SaveData(this ISaveAsJson source, JSON mainData)
    {
        JSON saveData = source.Save();

        saveData.AddOrReplace(VersionKey, source.Version);
        mainData.Add(source.Key, saveData);
    }
コード例 #10
0
    public JSON Save()
    {
        JSON data = new JSON();

        data.Add("ClipName", _animationClip != null?_animationClip.name:"null");
        return(data);
    }
コード例 #11
0
        public JSON GetSaveData()
        {
            JSON rValue = new JSON();

            rValue.Add("value", Value.GetSaveData());
            return(rValue);
        }
コード例 #12
0
ファイル: SaveAndLoadFile.cs プロジェクト: enginerds/EQual
        private void Test()
        {
            // Create JSON object for testing
            JSON originalObject = new JSON();

            originalObject.Add("name", "Test Person");
            originalObject.Add("age", 42);

            // Save to text file
            saveJsonObjectToTextFile(originalObject);

            // Load from text file
            JSON loadedObject = loadTextFileToJsonObject();

            // Check that objects are equal
            Debug.Log("Loaded object equals original object: " + loadedObject.Equals(originalObject));
        }
コード例 #13
0
    public static void Save()
    {
        JSON data = new JSON();

        foreach (KeyValuePair <string, JSON> pair in Instance._characters)
        {
            data.Add(pair.Key, pair.Value);
        }

        SaveLoadManager.SaveEncryptedJson(data, Instance.fileName);
    }
コード例 #14
0
    public JSON Save()
    {
        JSON   json  = new JSON();
        JArray array = new JArray();

        foreach (GameObject go in equipment)
        {
            array.Add(go.name);
        }
        json.Add("Equipment", array);
        return(json);
    }
コード例 #15
0
        public override JSON Export()
        {
            JSON baseExport = base.Export();
            JSON parameters = JSON.CreateArray();

            foreach (var paramInfo in Parameters)
            {
                JSON paramJSON = paramInfo.Export();
                parameters.Add(paramJSON);
            }
            baseExport["parameters"] = parameters;
            return(baseExport);
        }
コード例 #16
0
ファイル: RSLibrary.cs プロジェクト: BeauPrime/RuleScript
        public JSON Export()
        {
            JSON root = JSON.CreateObject();

            JSON components = JSON.CreateArray();

            foreach (var componentInfo in m_Components.Values)
            {
                components.Add(componentInfo.Export());
            }

            JSON triggers = JSON.CreateArray();

            foreach (var triggerInfo in m_Triggers.Values)
            {
                triggers.Add(triggerInfo.Export());
            }

            JSON queries = JSON.CreateArray();

            foreach (var queryInfo in m_Queries.Values)
            {
                queries.Add(queryInfo.Export());
            }

            JSON actions = JSON.CreateArray();

            foreach (var actioninfo in m_Actions.Values)
            {
                actions.Add(actioninfo.Export());
            }

            JSON groups = JSON.CreateArray();

            foreach (var groupInfo in m_Groups.Values)
            {
                groups.Add(groupInfo.Export());
            }

            root["components"] = components;
            root["triggers"]   = triggers;
            root["queries"]    = queries;
            root["actions"]    = actions;
            root["groups"]     = groups;

            return(root);
        }
コード例 #17
0
 // if isNewAttempt is false,  then look for current Teacher Action and use that to replace the data/ add data to that object
 public bool SetTeacherActionData(string key, string value, bool isNewAttempt = false)
 {
     if (currentSecnarioMasterKey != "")
     {
         if (isNewAttempt)
         {
             if (key != null && key != "")
             {
                 if (key != "TeacherActionSelected" && key != "TA1" && key != "TA2" && key != "TASQuestion" && key != "TASTimeStarted" && key != "Model" && key != "Revision")
                 {
                     Debug.LogAssertion("Key for New attepmt of Teacher Action is not an expected key");
                     return(false);
                 }
                 currentTAS = LogData.GetJSON(currentSecnarioMasterKey).GetJSON("TeacherActions").GetJArray("TASData").Length;
                 JSON TeacherSubActionsObject = new JSON(); // inner object of Teacher Sub Action
                 TeacherSubActionsObject.Add(key, value);
                 LogData.GetJSON(currentSecnarioMasterKey).GetJSON("TeacherActions").GetJArray("TASData").Add(TeacherSubActionsObject);
                 //currentTASData.Add(TeacherSubActionsObject);
                 logDataUpdated = true;
                 return(true);
             }
             Debug.LogAssertion("Key for New attepmt of Teacher Action is empty or null");
             return(false);
         }
         else
         {
             if (key != null && key != "")
             {
                 if (key != "TeacherActionSelected" && key != "TA1" && key != "TA2" && key != "TASQuestion" && key != "TASTimeStarted" && key != "Model" && key != "Revision" && key != "TASTimeFinished" && key != "TASComment")
                 {
                     Debug.LogAssertion("Key for adidng or replacning a part of exiting of Teacher Action is not an expected key");
                     return(false);
                 }
                 LogData.GetJSON(currentSecnarioMasterKey).GetJSON("TeacherActions").GetJArray("TASData").GetJSON(currentTAS).AddOrReplace(key, value);
                 //currentTASData.GetJSON(currentTAS).AddOrReplace(key, value);
                 logDataUpdated = true;
                 return(true);
             }
             Debug.LogAssertion("Key for adidng or replacning a part of exiting of Teacher Action is empty or null");
             return(false);
         }
     }
     Debug.LogAssertion("Please use SetScenarioMasterLogObject with appropriate key to start logging this into the correct scenario");
     return(false);
 }
コード例 #18
0
        public override JSON Export()
        {
            JSON json = base.Export();

            JSON fields = JSON.CreateArray();

            if (m_PersistFields != null)
            {
                foreach (var field in m_PersistFields.Values)
                {
                    fields.Add(field.Export());
                }
            }

            json["persistFields"] = fields;

            return(json);
        }
コード例 #19
0
 public static bool Key(ref string data, int i, ref JSON json)
 {
     if (i < data.Length)
     {
         if ((data[i] == '"' || data[i] == '\''))
         {
             onKey = false;
             json.Add(key, null);
             return(Prop(ref data, i + 1, ref json));
         }
         else
         {
             key += data[i];
             return(Key(ref data, i + 1, ref json));
         }
     }
     return(false);
 }
コード例 #20
0
        public JObject SetJSON(String GroupKey, String Key, Object Value)
        {
            lock (_UserDefined)
            {
                if (_UserDefined.TryGet(GroupKey, out Object JValue))
                {
                    if (JValue is JObject JSON)
                    {
                        JSON.Add(new JProperty(Key, Value));
                        return(JSON);
                    }

                    return(null);
                }

                var JSON2 = new JObject();
                _UserDefined.Set(GroupKey, JSON2);
                JSON2.Add(new JProperty(Key, Value));
                return(JSON2);
            }
        }
コード例 #21
0
    // this has to be called per scenario at start of the scenario, as it creates the basic Empty object for a scenario with its key structures
    // better to be called after the PlayerID is set from GameManager, as this attempts to find an existing User file with same date to modify , or else it create a new one
    public bool SetScenarioMasterLogObject(string key)
    {
        if (LogData == null)
        {
            Init();
        }

        if (key != null && key != "")
        {
            currentSecnarioMasterKey = key;
            currentTAS = 0;


            if (currentSecnarioMasterKey != "")
            {
                // initiate basics Log object Arrays
                JArray TASData                   = new JArray();
                JArray PlayerLookingAtData       = new JArray();
                JArray PlayerMovedToData         = new JArray();
                JArray PlayerSelectedStudentData = new JArray();
                JArray StudentLookingAtData      = new JArray();
                JArray StudentAnimationsData     = new JArray();
                JArray StudentSetupData          = new JArray();


                JSON ScenarioMasterObject = new JSON();

                JSON TeacherActionsObject = new JSON();
                JSON PlayerActionsObject  = new JSON();
                JSON StudentActionsObject = new JSON();

                JSON GettingToKnowYourClassObject = new JSON();

                JSON InitialSituationObject = new JSON();

                // Populate TeacherActions
                TeacherActionsObject.AddOrReplace("TASData", TASData);

                // Populate PlayerActions
                PlayerActionsObject.AddOrReplace("LookingAt", PlayerLookingAtData);
                PlayerActionsObject.AddOrReplace("MovedTo", PlayerMovedToData);
                PlayerActionsObject.AddOrReplace("SelectedStudent", PlayerSelectedStudentData);

                // Populate StudentActions
                StudentActionsObject.AddOrReplace("LookingAt", StudentLookingAtData);
                StudentActionsObject.AddOrReplace("Animations", StudentAnimationsData);

                // Populate GettingToKnowYourClassObject
                GettingToKnowYourClassObject.AddOrReplace("start1", "");
                GettingToKnowYourClassObject.AddOrReplace("end1", "");

                // Populate InitialSituationObject
                InitialSituationObject.AddOrReplace("start2", "");
                InitialSituationObject.AddOrReplace("end2", "");

                // Add all the above and StudentSetup to the Current Scenario Object
                ScenarioMasterObject.AddOrReplace("GettingToKnowYourClass", GettingToKnowYourClassObject);
                ScenarioMasterObject.AddOrReplace("InitialSituation", InitialSituationObject);

                ScenarioMasterObject.AddOrReplace("TeacherActions", TeacherActionsObject);
                ScenarioMasterObject.AddOrReplace("StudentSetup", StudentSetupData);
                ScenarioMasterObject.AddOrReplace("PlayerActions", PlayerActionsObject);
                ScenarioMasterObject.AddOrReplace("StudentActions", StudentActionsObject);



                if (LogData.ContainsKey(currentSecnarioMasterKey))
                {
                    LogData.AddOrReplace(currentSecnarioMasterKey, ScenarioMasterObject);
                }
                else
                {
                    LogData.Add(currentSecnarioMasterKey, ScenarioMasterObject);
                }
            }
            return(true);
        }
        currentSecnarioMasterKey = "";
        Debug.LogAssertion("Key for New attepmt to set Scenario Master Log Object is empty or null");
        return(false);
    }
コード例 #22
0
    public JSON Save()
    {
        JSON json = new JSON();

        json.Add("Primary", primary.AsJson());
        json.Add("Secondary", secondary.AsJson());
        json.Add("LeatherPrimary", leatherPrimary.AsJson());
        json.Add("MetalPrimary", metalPrimary.AsJson());
        json.Add("LeatherSecondary", leatherSecondary.AsJson());
        json.Add("MetalDark", metalDark.AsJson());
        json.Add("MetalSecondary", metalSecondary.AsJson());
        json.Add("Hair", hair.AsJson());
        json.Add("Skin", skin.AsJson());
        json.Add("Stubble", stubble.AsJson());
        json.Add("Scar", scar.AsJson());
        json.Add("BodyArt", bodyArt.AsJson());
        json.Add("Eyes", eyes.AsJson());

        return(json);
    }
コード例 #23
0
ファイル: Payment.cs プロジェクト: gishowm/WeiXin.dll
        //企业付款
        public static JSON EnterprisePayment(string partner_trade_no, string openid, int amount, string re_user_name, string desc)
        {
            ///请求的URL
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            //获取证书,证书位置放在根目录不安全。
            string cert     = HttpContext.Current.Server.MapPath("/!/apiclient_cert.p12");
            string password = WeiXin.Config.Pay_Memberid;

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //获取证书
            //X509Certificate cer = new X509Certificate(cert, password);
            X509Certificate2 cer        = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);//线上发布需要添加
            HttpWebRequest   webrequest = (HttpWebRequest)HttpWebRequest.Create(url);

            //添加证书
            webrequest.ClientCertificates.Add(cer);
            //创建web请求。
            webrequest.Method = "post";
            string[] parameters =
            {
                "mch_appid=" + WeiXin.Config.Pay_AppID,
                "mchid=" + WeiXin.Config.Pay_Memberid,
                "nonce_str=" + Guid.NewGuid().ToString("N"),
                "partner_trade_no=" + partner_trade_no,
                "openid=" + openid,
                "check_name=NO_CHECK",
                "re_user_name=" + re_user_name,
                "amount=" + amount,
                "desc=" + desc,
                "spbill_create_ip=" + (Current.HOST == "localhost"?"220.115.186.146":Current.IP)
            };
            string xmlstring = MakeXML(parameters);

            byte[] bs = Encoding.UTF8.GetBytes(xmlstring);
            //参数
            using (Stream reqStream = webrequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
            Stream          stream     = webreponse.GetResponseStream();
            string          resp       = string.Empty;
            Encoding        encoding   = Encoding.UTF8;

            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                resp = reader.ReadToEnd();
            }
            XmlDocument xml = new XmlDocument();

            xml.LoadXml(resp);
            if (xml.SelectSingleNode("/xml/return_code").InnerText.Equals("SUCCESS"))
            {
                if (xml.SelectSingleNode("/xml/result_code").InnerText.Equals("SUCCESS"))
                {
                    JSON retMsg = new JSON();
                    try
                    {
                        retMsg.Add("partner_trade_no", xml.SelectSingleNode("/xml/partner_trade_no").InnerText);
                        retMsg.Add("payment_no", xml.SelectSingleNode("/xml/payment_no").InnerText);
                        retMsg.Add("payment_time", xml.SelectSingleNode("/xml/payment_time").InnerText);
                        return(retMsg);
                    }
                    catch (Exception)
                    {
                        return(null);
                    }
                }
                else
                {
                    switch (xml.SelectSingleNode("/xml/err_code").InnerText)
                    {
                    case "NOAUTH": throw new Exception("没有权限");

                    case "AMOUNT_LIMIT": throw new Exception("付款金额不能小于最低限额");

                    case "PARAM_ERROR": throw new Exception("参数错误");

                    case "OPENID_ERROR": throw new Exception("Openid错误");

                    case "NOTENOUGH": throw new Exception("系统余额不足");

                    case "SYSTEMERROR": throw new Exception("系统繁忙,请稍后再试");

                    case "NAME_MISMATCH": throw new Exception("姓名校验出错");

                    case "SIGN_ERROR": throw new Exception("签名错误");

                    case "XML_ERROR": throw new Exception("Post内容出错");

                    case "FATAL_ERROR": throw new Exception("两次请求参数不一致");

                    case "CA_ERROR": throw new Exception("证书出错");

                    case "V2_ACCOUNT_SIMPLE_BAN": throw new Exception("非实名用户账号不可发放");
                    }
                }
            }
            throw new Exception(xml.SelectSingleNode("/xml/return_msg").InnerText);
            //throw new Exception(resp);
        }
コード例 #24
0
ファイル: Payment.cs プロジェクト: gishowm/WeiXin.dll
        //发红包
        public static JSON SendRedPack(string partner_trade_no, string openid, int amount, string desc, string act_name)
        {
            ///请求的URL
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //获取证书,证书位置放在根目录不安全。
            string cert     = HttpContext.Current.Server.MapPath("/!/apiclient_cert.p12");
            string password = WeiXin.Config.Pay_Memberid;

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //获取证书
            //X509Certificate cer = new X509Certificate(cert, password);
            X509Certificate2 cer        = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);//线上发布需要添加
            HttpWebRequest   webrequest = (HttpWebRequest)HttpWebRequest.Create(url);

            //添加证书
            webrequest.ClientCertificates.Add(cer);
            //创建web请求。
            webrequest.Method = "post";
            string[] parameters =
            {
                "wxappid=" + WeiXin.Config.Pay_AppID,
                "mch_id=" + WeiXin.Config.Pay_Memberid,
                "send_name=" + WeiXin.Config.SendName,
                "nonce_str=" + Guid.NewGuid().ToString("N"),
                "mch_billno=" + partner_trade_no,
                "re_openid=" + openid,
                "total_amount=" + amount,
                "total_num=" + 1,
                "act_name=" + act_name ?? "恭喜发财",
                "wishing=" + "恭喜发财",
                "client_ip=" + (Current.HOST == "localhost"?"220.115.186.146":Current.IP)
            };
            string xmlstring = MakeXML(parameters);

            byte[] bs = Encoding.UTF8.GetBytes(xmlstring);
            //参数
            using (Stream reqStream = webrequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
            Stream          stream     = webreponse.GetResponseStream();
            string          resp       = string.Empty;
            Encoding        encoding   = Encoding.UTF8;

            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                resp = reader.ReadToEnd();
            }
            XmlDocument xml = new XmlDocument();

            xml.LoadXml(resp);
            if (xml.SelectSingleNode("/xml/return_code").InnerText.Equals("SUCCESS"))
            {
                if (xml.SelectSingleNode("/xml/result_code").InnerText.Equals("SUCCESS"))
                {
                    switch (xml.SelectSingleNode("/xml/result_code").InnerText)
                    {
                    case "SUCCESS":
                        JSON retMsg = new JSON();
                        try
                        {
                            retMsg.Add("partner_trade_no", xml.SelectSingleNode("/xml/partner_trade_no").InnerText);
                            retMsg.Add("payment_no", xml.SelectSingleNode("/xml/payment_no").InnerText);
                            retMsg.Add("payment_time", xml.SelectSingleNode("/xml/payment_time").InnerText);
                            return(retMsg);
                        }
                        catch (Exception)
                        {
                            return(null);
                        }

                    case "NOAUTH": throw new Exception("没有权限");

                    case "SENDNUM_LIMIT": throw new Exception("该用户今日领取红包个数超过限制");

                    case "ILLEGAL_APPID": throw new Exception("错误传入了app的appid");

                    case "MONEY_LIMIT": throw new Exception("Openid错误");

                    case "SEND_FAILED": throw new Exception("系统余额不足");

                    case "FATAL_ERROR": throw new Exception("系统繁忙,请稍后再试");

                    case "NAME_MISMATCH": throw new Exception("姓名校验出错");

                    case "SIGN_ERROR": throw new Exception("签名错误");

                    case "XML_ERROR": throw new Exception("Post内容出错");

                    case "CA_ERROR": throw new Exception("证书出错");

                    case "NOTENOUGH": throw new Exception("账户余额不足");

                    case "OPENID_ERROR": throw new Exception("openid和appid不匹配");

                    case "MSGAPPID_ERROR": throw new Exception("msgappid与主、子商户号的绑定关系校验失败");

                    case "PROCESSING": throw new Exception("发红包流程正在处理");
                    }
                }
            }
            throw new Exception(xml.SelectSingleNode("/xml/return_msg").InnerText);
            //throw new Exception(resp);
        }
コード例 #25
0
        /// <summary>
        /// Parse JSON string to key value pairs
        /// </summary>
        /// <param name="rawjson">JSON String</param>
        /// <returns>Key value pairs data</returns>
        public static JSON Parse(string rawjson)
        {
            JSON          outdict            = new JSON();
            StringBuilder keybufferbuilder   = new StringBuilder();
            StringBuilder valuebufferbuilder = new StringBuilder();
            StringReader  bufferreader       = new StringReader(rawjson);

            int  s             = 0;
            bool reading       = false;
            bool inside_string = false;
            bool reading_value = false;

            //break at end (returns -1)
            while (s >= 0)
            {
                s = bufferreader.Read();
                //opening of json
                if (!reading)
                {
                    if ((char)s == '{' && !inside_string && !reading)
                    {
                        reading = true;
                    }
                    continue;
                }
                else
                {
                    //if we find a quote and we are not yet inside a string, advance and get inside
                    if (!inside_string)
                    {
                        //read past the quote
                        if ((char)s == '\"')
                        {
                            inside_string = true;
                        }
                        continue;
                    }
                    if (inside_string)
                    {
                        //if we reached the end of the string
                        if ((char)s == '\"')
                        {
                            inside_string = false;
                            s             = bufferreader.Read(); //advance pointer
                            if ((char)s == ':')
                            {
                                reading_value = true;
                                continue;
                            }
                            if (reading_value && (char)s == ',')
                            {
                                //we know we just ended the line, so put itin our dictionary
                                if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                {
                                    outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                                }
                                //and clear the buffers
                                keybufferbuilder.Clear();
                                valuebufferbuilder.Clear();
                                reading_value = false;
                            }
                            if (reading_value && (char)s == '}')
                            {
                                //we know we just ended the line, so put itin our dictionary
                                if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                {
                                    outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                                }
                                //and clear the buffers
                                keybufferbuilder.Clear();
                                valuebufferbuilder.Clear();
                                reading_value = false;
                                reading       = false;
                                break;
                            }
                        }
                        else
                        {
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                                continue;
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                                continue;
                            }
                        }
                    }
                    else
                    {
                        switch ((char)s)
                        {
                        case ':':
                            reading_value = true;
                            break;

                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                        }
                    }
                }
            }
            return(outdict);
        }
コード例 #26
0
        private void Test1()
        {
            // Create empty JSON object "{}"
            JSON jsonObject = new JSON();

            // Add this JSON object to debug
            // After this call, you can see content of this JSON object in Unity Editor, by choosing "Window -> Total JSON -> JSON Runtime Debug" from Unity menu
            // For debug/development purposes it is very handy to see contents of JSON objects while application is running in editor
            jsonObject.DebugInEditor("CreateAndModify Test JSON");

            Debug.Log("Note! You can see the content of selected JSON objects while application is running by choosing \"Window -> Total JSON -> JSON Runtime Debug\" from Unity menu");

            // Add basic things
            jsonObject.Add("text", "Hello World!");
            jsonObject.Add("number", 42);
            jsonObject.Add("truth", true);
            jsonObject.Add("nullText", null);
            jsonObject.Add("numberArray", new int[] { 1, 2, 4, 8 });

            // Print out
            Debug.Log(jsonObject.CreateString());             // {"text":"Hello World!","number":42,"truth":true,"nullText":null,"numberArray":[1,2,4,8]}

            // Do some changes
            jsonObject.Remove("number");
            jsonObject.Replace("truth", false);

            // Loop through all the keys and print out debug info of all values
            Debug.Log("Info of all the values:");
            foreach (string key in jsonObject.Keys)
            {
                Debug.Log(key + ": " + jsonObject[key]);
            }

            // Loop through all the keys and print out all values in JSON formatted strings
            Debug.Log("Content of all the values:");
            foreach (string key in jsonObject.Keys)
            {
                Debug.Log(key + " -> " + jsonObject[key].CreateString());
            }

            // Get and print out some values
            Debug.Log("Print outs of some values:");
            Debug.Log(jsonObject.GetString("text"));            // "Hello World!"
            Debug.Log(jsonObject.ContainsKey("number"));        // false
            Debug.Log(jsonObject.GetBool("truth"));             // false
            Debug.Log(jsonObject.GetString("nullText"));        // Null

            // Do some changes to array
            JArray jsonArray = jsonObject.GetJArray("numberArray"); // Contains ints 1,2,4,8

            jsonArray.Add(16);                                      // 1,2,4,8,16
            jsonArray.RemoveAt(1);                                  // 1,4,8,16
            jsonArray.InsertAt(3, 0);                               // 1,4,8,0,16
            jsonArray.ReplaceAt(2, -1);                             // 1,4,-1,0,16

            // Print out some array values
            Debug.Log("Array length: " + jsonArray.Length);            // 5
            Debug.Log("Fifth element as int: " + jsonArray.GetInt(4)); // 16

            // Since all values in array are numbers (JNumber) and they all fit to c# int values, array can be also copied to system int array
            int[] systemIntArray = jsonArray.AsIntArray();
            // Print out values
            Debug.Log("Second element as int: " + systemIntArray[1]);           // 4
        }
コード例 #27
0
        // TODO: This actually never returns null atm
        internal static JValue serializeObject(object obj, SerializeSettings serializeSettings)
        {
            JValue singleValue = singleObjectAsJValue(obj);

            if (singleValue != null)
            {
                return(singleValue);
            }

            if (obj is IList)
            {
                JArray jArray = new JArray();
                IList  list   = (IList)(obj);
                for (int n = 0; n < list.Count; n++)
                {
                    JValue jValue = serializeObject(list[n], serializeSettings);
                    if (jValue == null)
                    {
                        throw (new SerializeException("List item is type that can't be serialized", list[n]));
                    }
                    jArray.Add(jValue);
                }
                return(jArray);
            }

            Type type = obj.GetType();

            if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(Dictionary <,>))
                {
                    JSON   json            = new JSON();
                    Type[] dictTypes       = type.GetGenericArguments();
                    bool   dictKeyIsString = (dictTypes[0] == typeof(string));
                    if (!serializeSettings.AllowNonStringDictionaryKeys && !dictKeyIsString)
                    {
                        throw (new SerializeException("Dictionary key is type ('" + dictTypes[0] + "') that can't be serialized. Dictionary keys must be strings, or allow more loose options using SerializeSettings"));
                    }
                    IDictionary dict = (IDictionary)(obj);
                    foreach (object objectKey in dict.Keys)
                    {
                        JValue jValue = serializeObject(dict[objectKey], serializeSettings);
                        if (jValue == null)
                        {
                            throw (new SerializeException("Dictionary item is type that can't be serialized", dict[objectKey]));
                        }
                        string stringKey;
                        if (dictKeyIsString)
                        {
                            stringKey = (string)(objectKey);
                        }
                        else
                        {
                            stringKey = objectKey.ToString();
                        }
                        json.Add(stringKey, jValue);
                    }
                    return(json);
                }
            }

            JSON jsonSer = new JSON();

            FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                if (isSerializing(fieldInfo))
                {
                    string fieldName        = fieldInfo.Name;
                    object fieldToSerialize = fieldInfo.GetValue(obj);
                    JValue jValue           = serializeObject(fieldToSerialize, serializeSettings);
                    if (jValue == null)
                    {
                        throw (new SerializeException("Field \"" + fieldName + "\" is type that can't be serialized", fieldToSerialize));
                    }
                    jsonSer.Add(fieldName, jValue);
                }
            }

            return(jsonSer);
        }