ToString() public method

public ToString ( ) : string
return string
コード例 #1
0
 // GetExtraProperties, GetFullProeperties, GetDeepProperties
 public static SimpleJSON.JSONClass GetUeoBaseProps(SimpleJSON.JSONClass obj, UserEditableObject ueo, SceneSerializationType serializationType)
 {
     // oops -- we are setting "all" the properties including rotation and position. This SHOULD be warpped in USerEditableObject but we didn't do it that way
     // and a refactor would risk breaking existing levels,
     // so for now we leave ueo.setprops / ueo.getprops as a "higher level" properties, where as THIS BaseProps is the "full" properties of the object
     if (obj == null)
     {
         Debug.LogError("null obj");
         return(obj);
     }
     else if (ueo == null)
     {
         Debug.LogError("ueo null for " + obj["name"] + ", str;" + obj.ToString());
         return(obj);
     }
     obj["name"]          = ueo.GetName;
     obj["position"]      = JsonUtil.GetTruncatedPosition(ueo.transform);
     obj["rotation"]      = JsonUtil.GetRotation(ueo.transform);
     obj["active"].AsBool = ueo.gameObject.activeSelf;
     if (serializationType == SceneSerializationType.Instance)
     {
         obj[JsonUtil.scaleKey].AsInt = JsonUtil.GetScaleAsInt(ueo.transform);
     }
     obj["properties"] = ueo.GetProperties();
     return(obj);
 }
コード例 #2
0
ファイル: FloorButton.cs プロジェクト: ubberkid/PeerATT
	public void sendAction() {

		GetComponent<Animator>().Play("Click");

		if (buttonType == FLOOR_BUTTON_TYPE.YES || buttonType == FLOOR_BUTTON_TYPE.NO) {

			GameObject.Find("Debug Text").GetComponent<Text>().text += "Setting Position \n";

			HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/action"), HTTPMethods.Put, actionSentCallback);

			JSONClass data = new JSONClass();

			data["value"] = ((int)buttonType).ToString();

			request.AddHeader("Content-Type", "application/json");
			//request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
			request.RawData = Encoding.UTF8.GetBytes(data.ToString());
			request.Send();
		} else {

			HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/dlswitch"), HTTPMethods.Put, actionSentCallback);

			JSONClass data = new JSONClass();

			data["value"] = (dlSwitch).ToString();

			request.AddHeader("Content-Type", "application/json");
			//request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
			request.RawData = Encoding.UTF8.GetBytes(data.ToString());
			request.Send();
		}



	}
コード例 #3
0
    /// <summary>基础信息录入 - 建筑信息(按区块为单位上传)</summary>
    public static void UploadBlockInfo(string block_id, string buildings_sinfo, Action <string> callback, Action <HttpResp.ErrorType, string> failCallback = null)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["block_id"]       = block_id;
        jclass["buildings_info"] = buildings_sinfo;
        string strJson = jclass.ToString();

        WWWManager.Instance.Post("block_details/update_detail", strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                callback(resp.WwwText);
            }
            else
            {
                if (failCallback != null)
                {
                    failCallback(resp.Error, resp.WwwText);
                }
                else
                {
                    Debug.LogError("ERROR: " + resp.Error + ", " + resp.WwwText);
                }
            }
        });
    }
コード例 #4
0
ファイル: Tracker.cs プロジェクト: devangkantharia/memogames
        public void readHosts()
        {
            string path = Application.persistentDataPath;

            if (!path.EndsWith("/"))
            {
                path += "/";
            }

            PlayerPrefs.Save();
            //PlayerPrefs.DeleteAll();

            SimpleJSON.JSONNode hostfile = new SimpleJSON.JSONClass();

#if !(UNITY_WEBPLAYER || UNITY_WEBGL)
            if (!System.IO.File.Exists("host.cfg"))
            {
                hostfile.Add("host", new SimpleJSON.JSONData("http://localhost:3000/api/proxy/gleaner/collector/"));
                hostfile.Add("trackingCode", new SimpleJSON.JSONData("asdasdasdasda"));
                System.IO.File.WriteAllText("host.cfg", hostfile.ToString());
            }
            else
            {
                hostfile = SimpleJSON.JSON.Parse(System.IO.File.ReadAllText("host.cfg"));
            }
#endif

            PlayerPrefs.SetString("host", hostfile["host"]);
            PlayerPrefs.SetString("trackingCode", hostfile["trackingCode"]);
            PlayerPrefs.Save();


            //End tracker data loading
        }
コード例 #5
0
    public void addGameVersion(string id)
    {
        JSONClass json = new JSONClass ();
        json.Add ("gameId", id);

        net.POST (url + "/" + id + "/versions" , System.Text.Encoding.UTF8.GetBytes (json.ToString ()), trackHeaders, new GameVersionCreatorListener ());
    }
コード例 #6
0
    public static void UpdateBuildingInfo(string _strBlockName, string _strNodeGUID, string _strJsData, Action <string> sCb, Action <string> fCb,
                                          SingleTargetType _sType = SingleTargetType.Building)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["block_name"] = _strBlockName;
        jclass["build_guid"] = _strNodeGUID;
        jclass["info"]       = _strJsData;
        string strJson = jclass.ToString();

        string strPort = "building_infos/upsert";

        Debug.LogWarning("更新,发送的Js:\n" + _strJsData);
        Debug.LogWarning(string.Format("更新:地块ID:{0}\n建筑gID:{1}", _strBlockName, _strNodeGUID));

        WWWManager.Instance.Post(strPort, strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                sCb(resp.ToString());
            }
            else
            {
                Debug.LogError(string.Format("更新建筑基础信息:{0},失败:{1}", _strNodeGUID, resp.WwwText));

                fCb(resp.WwwText);
            }
        });
    }
コード例 #7
0
    void UpdateSession(bool force = false)
    {
//		// commented Debug.Log("sending analytics;"); //+N.ToString());
        if (!force && ((N[Keys.worldDistanceMoved] == null ||
                        N[Keys.mouseMovedDistance] == null ||
                        N[Keys.worldDistanceMoved].AsFloat == 0 ||
                        N[Keys.mouseMovedDistance].AsFloat == 0
                        ) && (N[Keys.levelBuilderButtonPress] == null ||
                              N[Keys.levelBuilderButtonPress].AsArray.Count == 0)))
        {
            // Worldpos and mousepos zero distance, and also no editor buttons pressed -- oh my we must be idle!

            // Idle is now handled in JS. If a report is not sent (repeatedly) the js will recognize idle, so Unity doesn't need to detect idle
            // This way is better for a variety of reasons but mainly beacuse Unity will "pause" if user is not focused so no reports will be sent nor will an idle alert be sent.
        }
        else
        {
            StatsMonitor.StatsMonitor stats = FindObjectOfType <StatsMonitor.StatsMonitor>();
            int fps = -1;
            if (stats)
            {
                fps = stats.fps;
            }
            N[Keys.fps].AsInt = fps;
                        #if UNITY_EDITOR
//			Debug.Log("sending:"+N.ToString());
                        #else
            WebGLComm.inst.SendAnalytics(N.ToString());
                        #endif
        }
    }
コード例 #8
0
    public static void UploadStreet(string city_name, JSONNode city_info, Action <string> callback, Action <HttpResp.ErrorType, string> failCallback = null)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["name"] = city_name;
        jclass["info"] = city_info.ToString();
        string strJson = jclass.ToString();

        WWWManager.Instance.Post("roads/new_road", strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                callback(resp.WwwText);
            }
            else
            {
                if (failCallback != null)
                {
                    failCallback(resp.Error, resp.WwwText);
                }
                else
                {
                    Debug.LogError("修改街道失败: " + resp.Error + ", " + resp.WwwText);
                }
            }
        });
    }
コード例 #9
0
    public static void UploadCity(string city_id, string city_name, string prov_id, string isHot, string j_city_id, JSONNode birth_coordinate, Action <string> callback, Action <HttpResp.ErrorType, string> failCallback = null)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["name"]       = city_name;
        jclass["city"]       = city_id;
        jclass["prov_id"]    = prov_id;
        jclass["j_city_id"]  = j_city_id;
        jclass["is_hotcity"] = isHot;
        if (birth_coordinate != null)
        {
            jclass["birth_coordinate"] = birth_coordinate.ToString();
        }
        string strJson = jclass.ToString();

        WWWManager.Instance.Post("cities/update_city", strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                callback(resp.WwwText);
            }
            else
            {
                if (failCallback != null)
                {
                    failCallback(resp.Error, resp.WwwText);
                }
                else
                {
                    Debug.LogError("ERROR: " + resp.Error + ", " + resp.WwwText);
                }
            }
        });
    }
コード例 #10
0
	//JSON Format:

	/*
	{
		"session": {
			"id": "session1234",
			"player": "user123",
			"game": "game1",
			"version": "version 1.0"
		},
		
		"play_events" :
		[ 
		{  "time": "2015-02-17T22:43:45-5:00", "event": "PowerUp.FireBall", "value": "1.0", "level": "1-1"},
		{  "time": "2015-02-17T22:45:45-5:00", "event": "PowerUp.Mushroom", "value": "2.0", "level": "1-1"}
		 ]
	}
	*/

	public static string ToJSON(Gloggr_Report r)
	{
	
		JSONNode n = new JSONClass();
		
		
		
		n.Add ("session",  Gloggr_SessionHeader.ToJSONObject(r.session)  );
		
		JSONArray a = new JSONArray();
		
		foreach(Gloggr_PlayEvent e in r.play_events)
		{
			a.Add(Gloggr_PlayEvent.ToJSONObject(e));
		}
		
		n.Add ("play_events", a);
		
		return n.ToString();	
	
//		string json = JsonConvert.SerializeObject(e, Formatting.Indented);
//		//from Gloggr_SessionHeader.ToJSON
//		//json = Gloggr_SessionHeader.FormatJSONKeys(json);
//		//from Gloggr_PlayEvent.ToJSON
//		//json = Gloggr_PlayEvent.FormatJSONKeys(json);
//		return json;
	}
コード例 #11
0
    public void login(string user, string pass)
    {
        JSONClass json = new JSONClass ();
        json.Add ("username", new JSONData (this.user));
        json.Add ("password", new JSONData (this.pass));

        www = net.POST (baseurl + loginurl, System.Text.Encoding.UTF8.GetBytes (json.ToString ()), trackHeaders, new LoginListener ());
    }
コード例 #12
0
    public void addGame(string title, bool ispublic)
    {
        JSONClass json = new JSONClass ();
        json.Add ("title", new JSONData (title));
        json.Add ("public", new JSONData (ispublic));

        net.POST (url, System.Text.Encoding.UTF8.GetBytes (json.ToString ()), trackHeaders, new GameCreatorListener ());
    }
コード例 #13
0
    public static byte[] BuildMessageBytes_OppName()
    {
        SimpleJSON.JSONClass obj = new SimpleJSON.JSONClass();
        obj.Add("sender", AppWarp.localusername);
        obj.Add("type", "oppName");

        byte[] retVal = System.Text.Encoding.UTF8.GetBytes(obj.ToString());
        return retVal;
    }
コード例 #14
0
 public static byte[] BuildMessageBytes_Move( string piece, int gbi )
 {
     SimpleJSON.JSONClass moveObj = new SimpleJSON.JSONClass();
     moveObj.Add("gridBoxIndex", gbi);
     moveObj.Add("sender", AppWarp.localusername);
     moveObj.Add("piece", piece);
     moveObj.Add("type", "move");
     return System.Text.Encoding.UTF8.GetBytes(moveObj.ToString());
 }
コード例 #15
0
    public static byte[] BuildBytes_NewMatch()
    {
        SimpleJSON.JSONClass obj = new SimpleJSON.JSONClass();
        obj.Add("sender", AppWarp.localusername);
        obj.Add("type", "new_match");

        byte[] retVal = System.Text.Encoding.UTF8.GetBytes(obj.ToString());
        return retVal;
    }
コード例 #16
0
        void DisableRating()
        {
            JSONNode data = new JSONClass();
            data = JSON.Parse(EditorPrefs.GetString(keyName));

            data["active"].AsBool = false;
            data["counter"].AsInt = 0;
            EditorPrefs.SetString(keyName, data.ToString());
            this.Close();
        }
コード例 #17
0
    public void ReloadSceneWithCallbackWithCallback(CallbackTarget cbt, string callbackMethod)
    {
//		callbackTarget = cbt;

        WebGLComm.inst.Debug("Reloading scene callback fn/mthod: " + cbt + ",/" + callbackMethod);
        SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
        N[SceneManager.callbackKey]       = callbackMethod;
        N[SceneManager.callbackTargetKey] = GetStringFromCalbackTarget(cbt);
        PlayerPrefs.SetString(prefsKey, N.ToString());
        ReloadSceneWithCallback();
    }
コード例 #18
0
 void SaveClipboardToServer()
 {
     SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
     N[clipboardKey] = new SimpleJSON.JSONArray();
     for (int i = 0; i < 9; i++)
     {
         if (clipboardSnips[i] != null)
         {
             SimpleJSON.JSONClass item = new SimpleJSON.JSONClass();
             item[clipboardIndexKey].AsInt = i;
             item[clipboardJsonKey]        = clipboardSnips[i];
             N[clipboardKey].Add(item);
         }
     }
             #if UNITY_EDITOR
     PlayerPrefs.SetString("Clipboard", N.ToString());
             #else
     WebGLComm.inst.SaveClipboard(N.ToString());
             #endif
 }
コード例 #19
0
ファイル: AI.cs プロジェクト: alvinman/defendaman
    void UpdateAI(JSONClass packet)
    {
    
        Debug.Log("Received packet: " + packet.ToString());
        xCoord = packet["x"].AsFloat;
        yCoord = packet["y"].AsFloat;
        angleFacing = packet["facing"].AsFloat;
        Vector2 newPos = new Vector2(xCoord, yCoord);

        transform.rotation = Quaternion.AngleAxis((float)angleFacing, Vector3.forward);
    }
コード例 #20
0
ファイル: ExportProject.cs プロジェクト: Qn880914/IGGGame
    // 保存当前平台类型
    static void SavePlatform()
    {
        BuildTarget target = EditorUserBuildSettings.activeBuildTarget;

        BuildSetting(target);

        SimpleJSON.JSONClass json = new SimpleJSON.JSONClass();
        json.Add("platform", new SimpleJSON.JSONData((int)target));
        json.Add("version", new SimpleJSON.JSONData(ConstantData.mainVersion));

        IGG.FileUtil.SaveTextToFile(json.ToString(""), CommandHelper.OutputPath);
    }
コード例 #21
0
        static void Startup()
        {
            EditorApplication.update -= Startup;

            if (!EditorPrefs.HasKey(keyName))
            {
                JSONNode data = new JSONClass();
                data["active"].AsBool = true;
                EditorPrefs.SetString(keyName, data.ToString());
            }

            Count();
        }
    string SetRandomBody()
    {
        int bodInd = Random.Range(0, 2);

        SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
//		N["HatIndex"].AsInt = Random.Range(0,4);
        N["HairIndex"].AsInt      = Random.Range(0, 4);
        N["BodyIndex"].AsInt      = bodInd;
        N["HairColorIndex"].AsInt = Random.Range(0, allMaterials.Length);
        N["BodyColorIndex"].AsInt = Random.Range(0, allMaterials.Length);
        N["HeadColorIndex"].AsInt = Random.Range(0, allMaterials.Length);
        return(N.ToString());
    }
コード例 #23
0
ファイル: NameSaver.cs プロジェクト: Kryttax/BullyingGame
    public void SaveName()
    {
        string path = Application.persistentDataPath;

        PlayerPrefs.SetInt("PreTestEnd", 0);
        PlayerPrefs.SetInt("PostTestEnd", 0);
        PlayerPrefs.SetInt("TeaTestEnd", 0);

        if (!path.EndsWith("/"))
        {
            path += "/";
        }

        if (PlayerPrefs.HasKey("username") && PlayerPrefs.GetString("username") != t.text)
        {
            if (System.IO.File.Exists(path + "tracesRaw.csv"))
            {
                System.IO.File.AppendAllText(path + PlayerPrefs.GetString("username") + ".csv.backup", System.IO.File.ReadAllText(path + "tracesRaw.csv"));
                System.IO.File.Delete(path + "tracesRaw.csv");
            }
        }
        PlayerPrefs.SetString("username", t.text);
        PlayerPrefs.SetString("password", t.text);
        PlayerPrefs.Save();
        //PlayerPrefs.DeleteAll();

        SimpleJSON.JSONNode hostfile = new SimpleJSON.JSONClass();

#if !(UNITY_WEBPLAYER || UNITY_WEBGL)
        if (!System.IO.File.Exists("host.cfg"))
        {
            hostfile.Add("host", new SimpleJSON.JSONData("http://192.168.175.117:3000/api/proxy/gleaner/collector/"));
            hostfile.Add("trackingCode", new SimpleJSON.JSONData("57d81d5585b094006eab04d6ndecvjlvjss8aor"));
            System.IO.File.WriteAllText("host.cfg", hostfile.ToString());
        }
        else
        {
            hostfile = SimpleJSON.JSON.Parse(System.IO.File.ReadAllText("host.cfg"));
        }
#endif

        PlayerPrefs.SetString("host", hostfile["host"]);
        if (PlayerPrefs.GetString("ActivitiesTracking") == null)
        {
            PlayerPrefs.SetString("trackingCode", hostfile["trackingCode"]);
        }
        PlayerPrefs.Save();

        TrackerObject.SetActive(true);
        //End tracker data loading
    }
コード例 #24
0
ファイル: dbConnect.cs プロジェクト: jiangkuo888/ORP_beta
        public string connectToDb()
        {
            //make sure all the paramter has something
            if (!System.String.IsNullOrEmpty(function) && !System.String.IsNullOrEmpty(url) && parameterList.Count > 0 && valueList.Count > 0)
            {
                WebClient webClient = new WebClient();
                NameValueCollection formData = new NameValueCollection();
                var sendJSON = new JSONClass();

                //get the values to be sent to backend
                for (int i=0; i < parameterList.Count;i++)
                {
                    string key = (string)parameterList[i];
                    sendJSON["info"][key] = (string)valueList[i];
                }

                //send to backend
                sendJSON["function"] = this.function;
                formData["send"] = sendJSON.ToString();
                byte[] responseBytes = webClient.UploadValues(this.url, "POST", formData);
                string responsefromserver = Encoding.UTF8.GetString(responseBytes);
                Debug.Log(responsefromserver);

                //parse the return values
                var returnValue = JSONNode.Parse(responsefromserver);
                int error = Convert.ToInt32(returnValue["error"]);

                if (error != -1)
                {
                    //if got error, parse it and return the appropriate error message
                    string errorString = this.parseError(error);
                    return errorString;

                } else {

                    //if no error, return "SUCCESS NO RETURN" if only "TRUE" is returned by backend
                    this.jsonReturn = returnValue["result"][0].ToString();
                    if (String.Compare(this.jsonReturn, "\"TRUE\"") == 0)
                    {
                        return "SUCCESS NO RETURN";
                    } else {
                        return "SUCCESS";
                    }
                }

                //return "";

            }

            return "you did not insert a function/parameter/value";
        }
コード例 #25
0
    SimpleJSON.JSONClass SaveLevelClass()
    {
        WebGLComm.inst.Debug("<color=#09f>Saver:</color>.SaveLevelClass()");
        // Construct the json that will be sent to the server.
        SimpleJSON.JSONClass N = GetSerializedLevelClassJson();


        string screenshotData = Screenshotter.inst.GetCurrentScreenshotByteArrayAsString();

                #if UNITY_EDITOR
//		Debug.Log("editor save");
        PlayerPrefs.SetString("SavedClass", N.ToString());
        SaveLevelClassCallback();
                #endif
        WebGLComm.inst.SaveLevelClassToServer(JsonUtil.GetStringFromJson(N), screenshotData);

        return(N);
    }
コード例 #26
0
    public static byte[] BuildBytes_OnlineEvent( OnlineGameEvent _ge )
    {
        SimpleJSON.JSONClass obj = new SimpleJSON.JSONClass();
        obj.Add("sender", AppWarp.localusername);
        obj.Add("type", "online_event");
        obj.Add("gE", (int)_ge.gameEvent);
        if( _ge.gameEventProperty != null ) {
            obj.Add("hasEP", true);
            obj.Add("gEP", _ge.gameEventProperty);
        }
        else {
            obj.Add("hasEP", false);
            obj.Add("gEP", "");
        }

        byte[] retVal = System.Text.Encoding.UTF8.GetBytes(obj.ToString());
        return retVal;
    }
コード例 #27
0
    public void SaveCompletedQuest(Quest questToSave)
    {
        if (PlayerPrefs.HasKey ("CompletedQuests") == true) {
            JSONNode completedQuests = JSONClass.Parse(PlayerPrefs.GetString("CompletedQuests"));
            for(int i = 0; i < completedQuests["CompletedQuest"].Count; i++){
                if(completedQuests["CompletedQuests"][i] == questToSave.GetID().ToString()){
                    completedQuests["CompletedQuests"][-1] = questToSave.GetID().ToString();
                    PlayerPrefs.SetString("CompletedQuests", completedQuests.ToString());
                    return;
                }
            }
        }

        JSONClass completedQuestJSONNode = new JSONClass ();
        completedQuestJSONNode ["CompletedQuests"] [0] = questToSave.GetID ().ToString();
        PlayerPrefs.SetString("CompletedQuests", completedQuestJSONNode.ToString());
        return;
    }
コード例 #28
0
        static void Count()
        {
            JSONNode data = new JSONClass();
            data = JSON.Parse(EditorPrefs.GetString(keyName));

            if(data["active"].AsBool == false)
                return;

            double time = GenerateUnixTime();
            double diff = time - data["lastCheck"].AsDouble;
            if(diff < 20) return;

            data["lastCheck"].AsDouble = time;
            data["counter"].AsInt = data["counter"].AsInt + 1;
            EditorPrefs.SetString(keyName, data.ToString());

            if(data["counter"].AsInt > 10)
                Init();
        }
コード例 #29
0
	public string ToString (){
		JSONClass j = new JSONClass ();
		j.Add ("Id",new JSONData (id));
		j ["Name"] = Name;
		j.Add ("Rank",new JSONData (Rank));
		j.Add ("Era", new JSONData(Era));
		j.Add ("Type", new JSONData(Type));
		j.Add ("InitialIQ", new JSONData(InitialIQ));
		j.Add ("GainIQ", new JSONData(GainIQ));
		j.Add ("HighestIQ", new JSONData(HighestIQ));
		j.Add ("InitialLeadership", new JSONData(InitialLeadership));
		j.Add ("GainLv30Leadership", new JSONData(GainLv30Leadership));
		j.Add ("GainLv60Leadership", new JSONData(GainLv60Leadership));
		j.Add ("GainLv99Leadership", new JSONData(GainLv99Leadership));
		j.Add ("HighestLeadership", new JSONData (HighestLeadership));
		j.Add ("InitialPrestige", new JSONData (InitialPrestige));
		j.Add ("KnownFormation", new JSONData (KnownFormation));
		j.Add ("KnownKnowledge", new JSONData (KnownKnowledge));
		return j.ToString ();
	}
コード例 #30
0
    /// <summary>
    /// Update City Information
    /// </summary>
    /// <param name="_strCityName"></param>
    /// <param name="_strJsData"></param>
    /// <param name="sCb"></param>
    /// <param name="fCb"></param>
    public static void UpdateCityInfo(string _strCityName, string _strJsData, Action sCb, Action <HttpResp.ErrorType, string> fCb)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["name"]       = _strCityName;
        jclass["block_file"] = _strJsData;
        string strJson = jclass.ToString();

        WWWManager.Instance.Post("cities/update_city", strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                sCb();
            }
            else
            {
                fCb(resp.Error, resp.WwwText);
            }
        });
    }
コード例 #31
0
    /// <summary>
    /// 批量删除组件
    /// </summary>
    /// <param name="_strNames">组件ID字符串</param>
    /// <param name="_cb"></param>
    public static void DeleteCompConfig(string _strNames, Action <bool, HttpResp> _cb)
    {
        // 转为json
        var jclass = new SimpleJSON.JSONClass();

        jclass["name_list"] = _strNames;

        WWWManager.Instance.Post("components/drop_by_list", jclass.ToString(), resp =>
        {
            Debug.Log("删除结果返回:" + resp.WwwText);
            if (!HasRespError(resp))
            {
                _cb(true, resp);
            }
            else
            {
                _cb(false, resp);
            }
        });
    }
コード例 #32
0
    SimpleJSON.JSONClass SaveLevelInstance()
    {
        //Note that this was a performance bottleneck, NOT because of serialization (although that is still expensive)
        // but actually because of gettign a value of "string" out of Json object e.g. SimpleJson.ToString()
        //  Charlie improved performance by replacing tostring methods from string s = ""; s += "nextpiece" to StringBuilder sb = new StringBuilder(""); sb.append("nextpiece");
        // seems to speed up serialization (from existing complete SimpleJson.JsonCLASS object).ToString() A LOT e.g. 1 second to 0.2 seconds
        SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
        N = GetLevelMetaData();
        N = JsonSerializeSceneObjects(N, SceneSerializationType.Instance);


                #if UNITY_EDITOR
        PlayerPrefs.SetString("SavedInstance", N.ToString());
                #endif

        WebGLComm.inst.SaveLevelInstanceToServer(JsonUtil.GetStringFromJson(N));


        return(N);
    }
コード例 #33
0
    /// <summary>
    /// 保存组件配置
    /// </summary>
    /// <param name="_strName"></param>
    /// <param name="_strInfo"></param>
    /// <param name="_cb"></param>
    public static void SaveCompConfig(string _strName, string _strInfo, Action <bool, HttpResp> _cb)
    {
        // 转为json
        var jclass = new SimpleJSON.JSONClass();

        jclass["name"] = _strName;
        jclass["info"] = _strInfo;


        WWWManager.Instance.Post("components/set_info", jclass.ToString(), resp =>
        {
            if (!HasRespError(resp))
            {
                _cb(true, resp);
            }
            else
            {
                _cb(false, resp);
            }
        });
    }
コード例 #34
0
        public override string ToString()
        {
            var sj = new SimpleJSON.JSONClass();

            var jsonObj = new JSONClass();

            jsonObj.Add("AgentCount", new JSONData(AgentCount));

            var jsonArray = new JSONArray();

            lock (agents)
            {
                foreach (var agent in agents)
                {
                    jsonArray.Add("Agent", agent.Value.GetJsonStatus());
                }
            }
            jsonObj.Add("Agents", jsonArray);
            sj.Add("AgentStatus", jsonObj);
            return(sj.ToString());
        }
コード例 #35
0
    /// <summary>
    /// 保存临时数据接口
    /// </summary>
    /// <param name="_strName"></param>
    /// <param name="_strType"></param>
    /// <param name="_strInfo"></param>
    /// <param name="_cb"></param>
    public static void SaveTempData(string _strName, string _strType, string _strInfo, Action <bool, HttpResp> _cb)
    {
        // 转为json
        var jclass = new SimpleJSON.JSONClass();

        jclass["name"] = _strName;
        jclass["type"] = _strType;
        jclass["info"] = _strInfo;

        WWWManager.Instance.Post("temp_buildings/set_info", jclass.ToString(), resp =>
        {
            if (!HasRespError(resp))
            {
                _cb(true, resp);
            }
            else
            {
                _cb(false, resp);
            }
        });
    }
コード例 #36
0
    public static string GetJsonFromList(TimelineItemDataMeta tuple)
    {
        var sign = new JSONClass();

        foreach (var item in tuple.Data)
        {
            var i = new JSONClass();
            i["number"] = item.Number.ToString();
            i["facialExpression"] = item.FacialExpression.ToString();
            i["timestamp"] = item.Timestamp.ToString();
            i["duration"] = item.Duration.ToString();

            i["leftHand"] = item.LeftHand.ToJson();
            i["rightHand"] = item.RightHand.ToJson();
            sign["items"][-1] = i;
        }
        sign["metadata"] = tuple.MetaData.ToJson();

        var root = new JSONClass();
        root["sign"] = sign;
        return root.ToString();
    }
コード例 #37
0
    //Save each object properties to a JSON file

    /* JSON format:
     *      {
     *              "ObjectN": {
     *                      "Position" : {
     *                              "x" : Double,
     *                              "y": Double,
     *                              "z" : Double
     *                      },
     *                      "Rotation" : {
     *                              "x" : Double,
     *                              "y": Double,
     *                              "z" : Double
     *                      },
     *                      "Scale" : {
     *                              "x" : Double,
     *                              "y": Double,
     *                              "z" : Double
     *                      },
     *                      "Name" : String
     *              }
     *      }
     */
    private void SaveSceneToFile(string mazeName, List <ObjectSet> mazeSet)
    {
        SimpleJSON.JSONNode mazeJSON = new SimpleJSON.JSONClass();

        int i = 0;

        foreach (ObjectSet mazeObj in mazeSet)
        {
            //Debug.Log (mazeObj.name + " " + mazeObj.postion + " " + mazeObj.rotation + " " + mazeObj.scale);

            string objectName = "Object" + i;

            //JSON Format, creates the JSON format through the mazeJSON Node
            mazeJSON[objectName]["Position"]["x"].AsDouble = mazeObj.position.x;
            mazeJSON[objectName]["Position"]["y"].AsDouble = mazeObj.position.y;
            mazeJSON[objectName]["Position"]["z"].AsDouble = mazeObj.position.z;

            mazeJSON[objectName]["Rotation"]["x"].AsDouble = mazeObj.rotation.x;
            mazeJSON[objectName]["Rotation"]["y"].AsDouble = mazeObj.rotation.y;
            mazeJSON[objectName]["Rotation"]["z"].AsDouble = mazeObj.rotation.z;

            mazeJSON[objectName]["Scale"]["x"].AsDouble = mazeObj.scale.x;
            mazeJSON[objectName]["Scale"]["y"].AsDouble = mazeObj.scale.y;
            mazeJSON[objectName]["Scale"]["z"].AsDouble = mazeObj.scale.z;

            mazeJSON[objectName]["State"].AsInt = mazeObj.toggleState;

            mazeJSON[objectName]["Name"] = mazeObj.name;

            i++;
        }

        string fileDest = "Assets/Resources/Mazes/" + mazeName + ".txt";

        File.WriteAllText(fileDest, mazeJSON.ToString()); //Writes the JSON file

        UnityEditor.AssetDatabase.Refresh();              //Refresh the Editor, making changes immeadiate
    }
コード例 #38
0
    public static void DeleteSingleBuildingInfoByJson(string _strBlockName, string _strGUID, Action sCb, Action <string> fCb)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["block_name"] = _strBlockName;
        jclass["build_guid"] = _strGUID;
        string strJson = jclass.ToString();

        string strPort = "building_infos/delete";

        WWWManager.Instance.Post(strPort, strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                sCb();
            }
            else
            {
                Debug.LogWarning(string.Format("删除:{0},失败:{1}", strPort, resp.Error));
                fCb(resp.WwwText);
            }
        });
    }
コード例 #39
0
        public override string ToString()
        {
            var sj = new SimpleJSON.JSONClass();

            var jsonObj = new JSONClass();

            KeyValuePair <int, Actor>[] ad;
            lock (actorDict)
            {
                ad = actorDict.ToArray();
            }

            jsonObj.Add("ActorCount", new JSONData(ad.Length));
            var jsonArray = new JSONArray();

            foreach (var actor in ad)
            {
                var actorJson = new JSONClass();
                actorJson.Add("type", new JSONData(actor.Value.GetType().ToString()));
                var actorComponents = new JSONClass();

                /*
                 *  foreach (var compoent in actor.Value.GetComponents().Result)
                 *  {
                 *      actorComponents.Add("Component", new JSONData(compoent.GetType().ToString()));
                 *  }
                 */
                actorJson.Add("Components", actorComponents);
                actorJson.Add("Attribute", actor.Value.GetAttr());
                jsonArray.Add("Actor", actorJson);
            }
            jsonObj.Add("Actors", jsonArray);

            sj.Add("AtorStatus", jsonObj);
            return(sj.ToString());
        }
コード例 #40
0
        public void exportMethod()
        {
#if UNITY_EDITOR
            var astar = AstarPath.active;
            if (astar == null)
            {
                astar = GameObject.FindObjectOfType <AstarPath>();
            }
            string path = EditorUtility.SaveFilePanel("Save Graphs", "", "graph" + Convert.ToString(mapId) + ".zip", "zip");
            if (path != "")
            {
                if (EditorUtility.DisplayDialog("Scan before saving?", "Do you want to scan the graphs before saving" +
                                                "\nNot scanning can cause node data to be omitted from the file if Save Node Data is enabled", "Scan", "Don't scan"))
                {
                    astar.Scan();
                }


                //uint checksum;
                Pathfinding.Serialization.SerializeSettings settings = Pathfinding.Serialization.SerializeSettings.All;


                byte[] bytes = null;
                //uint ch = 0;
                astar.AddWorkItem(new AstarPath.AstarWorkItem(delegate(bool force) {
                    Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(astar.astarData, settings);
                    sr.OpenSerialize();
                    astar.astarData.SerializeGraphsPart(sr);
                    //sr.SerializeEditorSettings (graphEditors);
                    var start = GameObject.Find("PlayerStart").transform.position;
                    var grid  = Util.CoordToGrid(start.x, start.z);
                    var yOff  = Util.IntYOffset(start.y);

                    SimpleJSON.JSONClass jc = new SimpleJSON.JSONClass();
                    var arr = jc["playerStart"] = new SimpleJSON.JSONArray();

                    arr[-1].AsInt = (int)(grid.x);
                    arr[-1].AsInt = yOff;
                    arr[-1].AsInt = (int)(grid.y);

                    /*
                     * System.IO.MemoryStream stream = new System.IO.MemoryStream();
                     * BinaryWriter outfile = new BinaryWriter(stream);
                     * jc.Serialize(outfile);
                     */
                    Debug.Log("Export " + jc.ToString());
                    var graph = astar.graphs[0] as Pathfinding.GridGraph;
                    var js    = new SimpleJSON.JSONClass();
                    js["unclampedSize"]["x"].AsInt = graph.width;
                    js["unclampedSize"]["y"].AsInt = graph.depth;
                    js["center"]["x"].AsFloat      = graph.center.x;
                    js["center"]["y"].AsFloat      = graph.center.y;
                    js["center"]["z"].AsFloat      = graph.center.z;
                    sr.zip.AddEntry("playerStart" + Convert.ToString(mapId) + ".json", System.Text.Encoding.UTF8.GetBytes(jc.ToString()));
                    sr.zip.AddEntry("graph0.json", System.Text.Encoding.UTF8.GetBytes(js.ToString()));
                    bytes = sr.CloseSerialize();
                    //ch = sr.GetChecksum ();
                    return(true);
                }));

                Pathfinding.Serialization.AstarSerializer.SaveToFile(path, bytes);
                EditorUtility.DisplayDialog("Done Saving", "Done saving graph data.", "Ok");
            }
#endif
        }
コード例 #41
0
    /// <summary>
    /// 单粒度更新
    /// </summary>
    /// <param name="_strCityName"></param>
    /// <param name="_strJsData"></param>
    /// <param name="sCb"></param>
    /// <param name="fCb"></param>
    public static void UpdateSingleTargetByJson(string _strCityName, string _strJsData, Action <string> sCb, Action <string> fCb,
                                                SingleTargetType _sType = SingleTargetType.Building)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["block_name"] = _strCityName;
        jclass["info"]       = _strJsData;
        string strJson = jclass.ToString();

        string strPort = "Error";

        switch (_sType)
        {
        case SingleTargetType.Building:
            strPort = "buildings/upsert";
            break;

        case SingleTargetType.Component:
            strPort = "block_components/upsert";
            break;

        case SingleTargetType.Maps:
            strPort = "sub_blocks/upsert";
            break;

        case SingleTargetType.Shop:
            strPort = "shop_signs/upsert";
            break;

        case SingleTargetType.BuildingInfo:
            strPort = "building_infos/upsert";
            break;

        case SingleTargetType.StreetInfo:
            strPort             = "streets/upsert";
            jclass              = new SimpleJSON.JSONClass();
            jclass["city_name"] = _strCityName;
            jclass["info"]      = _strJsData;
            strJson             = jclass.ToString();
            break;

        default:
            return;
        }

        Debug.LogWarning("更新,发送的Js:\n" + _strJsData);

        WWWManager.Instance.Post(strPort, strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                sCb(resp.ToString());
            }
            else
            {
                Debug.LogError(string.Format("更新:{0},失败:{1}", _strCityName, resp.ToString()));

                fCb(resp.WwwText);
            }
        });
    }
コード例 #42
0
    /// <summary>
    /// 单粒度删除:_bType: 1-组件 2-建筑 3-九宫格
    /// </summary>
    /// <param name="_strCityName"></param>
    /// <param name="_strGUID"></param>
    /// <param name="sCb"></param>
    /// <param name="fCb"></param>
    /// <param name="_bType"></param>
    public static void DeleteSingleTargetByJson(string _strCityName, string _strGUID, Action sCb, Action <string> fCb,
                                                SingleTargetType _sType = SingleTargetType.Building, bool _bClearStreetID = false)
    {
        var jclass = new SimpleJSON.JSONClass();

        jclass["block_name"] = _strCityName;
        jclass["guid"]       = _strGUID;
        string strJson = jclass.ToString();

        string strPort = "Error";

        switch (_sType)
        {
        case SingleTargetType.Building:
            strPort = "buildings/delete";
            break;

        case SingleTargetType.Component:
            strPort = "block_components/delete";
            break;

        case SingleTargetType.Maps:
            strPort = "sub_blocks/delete";
            break;

        case SingleTargetType.Shop:
            strPort = "shop_signs/delete";
            break;

        case SingleTargetType.BuildingInfo:
            strPort = "building_infos/delete";
            break;

        case SingleTargetType.StreetInfo:

            strPort = "streets/delete";

            jclass = new SimpleJSON.JSONClass();
            jclass["city_name"]       = _strCityName;
            jclass["guid"]            = _strGUID;
            jclass["unbind_building"] = _bClearStreetID ? "true" : "false";
            strJson = jclass.ToString();
            break;

        default:
            return;
        }

        WWWManager.Instance.Post(strPort, strJson, resp =>
        {
            if (!HasRespError(resp))
            {
                sCb();
            }
            else
            {
                Debug.LogWarning(string.Format("删除:{0},失败:{1}", strPort, resp.Error));
                fCb(resp.WwwText);
            }
        });
    }
コード例 #43
0
        void OnGUI()
        {
            if(reviewWindowImage == null)
            {
                var script = MonoScript.FromScriptableObject(this);
                string path = Path.GetDirectoryName(AssetDatabase.GetAssetPath(script));
                reviewWindowImage = AssetDatabase.LoadAssetAtPath(path + imagePath, typeof(Texture2D)) as Texture2D;
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(31);
            GUILayout.Label(reviewWindowImage);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(48);
            EditorGUILayout.LabelField("Review Simple IAP System", GUILayout.Width(160));
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Please consider giving us a rating on the");
            EditorGUILayout.LabelField("Unity Asset Store. Your support helps us");
            EditorGUILayout.LabelField("to improve this product. Thank you!");

            GUILayout.Space(20);
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Rate now!"))
            {
                Help.BrowseURL("https://www.assetstore.unity3d.com/#!/content/12343");
                DisableRating();
            }
            if (GUILayout.Button("Later"))
            {
                JSONNode data = new JSONClass();
                data = JSON.Parse(EditorPrefs.GetString(keyName));
                data["counter"].AsInt = 5;

                EditorPrefs.SetString(keyName, data.ToString());
                this.Close();
            }
            if (GUILayout.Button("Never"))
            {
                DisableRating();
            }
            EditorGUILayout.EndHorizontal();
        }
コード例 #44
0
    void Test()
    {
        var N = SimpleJSON.JSONNode.Parse("{\"name\":\"test\", \"array\":[1,{\"data\":\"value\"}]}");

        N["array"][1]["Foo"] = "Bar";
        P("'nice formatted' string representation of the JSON tree:");
        P(N.ToString(""));
        P("");

        P("'normal' string representation of the JSON tree:");
        P(N.ToString());
        P("");

        P("content of member 'name':");
        P(N["name"]);
        P("");

        P("content of member 'array':");
        P(N["array"].ToString(""));
        P("");

        P("first element of member 'array': " + N["array"][0]);
        P("");

        N["array"][0].AsInt = 10;
        P("value of the first element set to: " + N["array"][0]);
        P("The value of the first element as integer: " + N["array"][0].AsInt);
        P("");

        P("N[\"array\"][1][\"data\"] == " + N["array"][1]["data"]);
        P("");

        var data  = N.SaveToBase64();
        var data2 = N.SaveToCompressedBase64();

        N = null;
        P("Serialized to Base64 string:");
        P(data);
        P("Serialized to Base64 string (compressed):");
        P(data2);
        P("");

        N = SimpleJSON.JSONNode.LoadFromBase64(data);
        P("Deserialized from Base64 string:");
        P(N.ToString());
        P("");

        var I = new SimpleJSON.JSONClass();

        I["version"].AsInt     = 5;
        I["author"]["name"]    = "Bunny83";
        I["author"]["phone"]   = "0123456789";
        I["data"][-1]          = "First item\twith tab";
        I["data"][-1]          = "Second item";
        I["data"][-1]["value"] = "class item";
        I["data"].Add("Forth item");
        I["data"][1] = I["data"][1] + " 'addition to the second item'";
        I.Add("version", "1.0");

        P("Second example:");
        P(I.ToString());
        P("");

        P("I[\"data\"][0]            : " + I["data"][0]);
        P("I[\"data\"][0].ToString() : " + I["data"][0].ToString());
        P("I[\"data\"][0].Value      : " + I["data"][0].Value);
        P(I.ToString());
    }
コード例 #45
0
ファイル: Test_CSharp.cs プロジェクト: ufukbal/mapquiz
    void Test()
    {
		TextAsset file = Resources.Load("CityInfo") as TextAsset;
		var node = JSON.Parse(file.text);
		var pl = node[0]["_id"];
		Debug.Log("TEST: " + pl);
		//var versionString = N["longitude"].Value;   
		var N1 = JSONNode.Parse("{\"name\":\"ankara\", \"array\":[1,{\"data\":\"value\"}]}");
		N1["array"][1]["x"] = "39.9";
		N1["array"][1]["y"] = "32.85";
		P(node[0]["_id"].ToString(""));

//        P("'nice formatted' string representation of the JSON tree:");
//        P(N1.ToString(""));
//        P("");
//
//        P("'normal' string representation of the JSON tree:");
//        P(N1.ToString());
//        P("");
//
//        P("content of member 'name':");
//        P(N1["name"]);
//        P("");
//
//        P("content of member 'array':");
//        P(N1["array"].ToString(""));
//        P("");
//
//		P("first element of member 'array': " + N1["array"][1]["x"].Value);
//        P("");
//
//        N["array"][0].AsInt = 10;
//        P("value of the first element set to: " + N1["array"][0]);
//        P("The value of the first element as integer: " + N1["array"][0].AsInt);
//        P("");
//
//        P("N[\"array\"][1][\"data\"] == " + N1["array"][1]["data"]);
//        P("");

       

        var I = new JSONClass();
        I["version"].AsInt = 5;
        I["author"]["name"] = "Bunny83";
        I["author"]["phone"] = "0123456789";
        I["data"][-1] = "First item\twith tab";
        I["data"][-1] = "Second item";
        I["data"][-1]["value"] = "class item";
        I["data"].Add("Forth item");
        I["data"][1] = I["data"][1] + " 'addition to the second item'";
        I.Add("version", "1.0");

        P("Second example:");
        P(I.ToString());
        P("");

        P("I[\"data\"][0]            : " + I["data"][0]);
        P("I[\"data\"][0].ToString() : " + I["data"][0].ToString());
        P("I[\"data\"][0].Value      : " + I["data"][0].Value);
		P (I.ToString());
    }
コード例 #46
0
    private IEnumerator UploadToServer()
    {
        JSONNode json = new JSONClass();
        json ["id"].AsInt = 2;
        json ["name"] = "Chicago Demo";
        json ["elements"].AsInt = quests.Count;

        //Add quests
        JSONArray questArray = new JSONArray ();
        int i = 0;
        foreach(Quest q in quests) {
            JSONNode questNode = new JSONClass();
            questNode["id"].AsInt = i+1;
            questNode["name"] = q.name;
            questNode["object"] = q.portal;
            questNode["type"].AsInt = q.type;
            questNode["media"] = q.media;
            questNode["points"].AsInt = q.points;
            questNode["scale"].AsInt = 1;
            questNode["map"] = "yes";
            questNode["pre"] = q.pre;
            questNode["answer"] = q.answer;
            questNode["post"] = q.post;
            questNode["lat"].AsFloat = q.location.lat;
            questNode["lon"].AsFloat = q.location.lon;
            questArray[i] = questNode;
            i++;
        }
        json ["objects"] = questArray;

        Debug.Log(json.ToString());
        //Debug.Log (json.SaveToBase64());
        string url = "http://www.mastercava.it/digitalquest/save_quest.php?data=" + WWW.EscapeURL (Convert.ToBase64String (Encoding.UTF8.GetBytes (json.ToString ())));
        Debug.Log (url);
        WWW www = new WWW (url);
        while (!www.isDone) {
            SetLoadingBar(www.progress);
            yield return null;
        }
        SetLoadingBar (1f);
    }
コード例 #47
0
    public IEnumerator writeSkinStats(int id, int kills)
    {
        JSONClass root = new JSONClass();
        JSONClass weapon = new JSONClass();

        weapon.Add("skin_id", "" + id);
        weapon.Add("kill_count", "" + kills);
        root.Add("skin_params", weapon);

        Debug.Log(root.ToString());
        byte[] data = Encoding.UTF8.GetBytes(root.ToString());
        WWW www = new WWW(ROOT_URL + POST_SKIN_URL, data);

        yield return WaitForRequest(www);
    }
コード例 #48
0
    void Test()
    {
        var N = JSONNode.Parse("{\"name\":\"test\", \"array\":[1,{\"data\":\"value\"}]}");
        N["array"][1]["Foo"] = "Bar";
        P("'nice formatted' string representation of the JSON tree:");
        P(N.ToString(""));
        P("");

        P("'normal' string representation of the JSON tree:");
        P(N.ToString());
        P("");

        P("content of member 'name':");
        P(N["name"]);
        P("");

        P("content of member 'array':");
        P(N["array"].ToString(""));
        P("");

        P("first element of member 'array': " + N["array"][0]);
        P("");

        N["array"][0].AsInt = 10;
        P("value of the first element set to: " + N["array"][0]);
        P("The value of the first element as integer: " + N["array"][0].AsInt);
        P("");

        P("N[\"array\"][1][\"data\"] == " + N["array"][1]["data"]);
        P("");

        var data = N.SaveToBase64();
        var data2 = N.SaveToCompressedBase64();
        N = null;
        P("Serialized to Base64 string:");
        P(data);
        P("Serialized to Base64 string (compressed):");
        P(data2);
        P("");

        N = JSONNode.LoadFromBase64(data);
        P("Deserialized from Base64 string:");
        P(N.ToString());
        P("");

        var I = new JSONClass();
        I["version"].AsInt = 5;
        I["author"]["name"] = "Bunny83";
        I["author"]["phone"] = "0123456789";
        I["data"][-1] = "First item\twith tab";
        I["data"][-1] = "Second item";
        I["data"][-1]["value"] = "class item";
        I["data"].Add("Forth item");
        I["data"][1] = I["data"][1] + " 'addition to the second item'";
        I.Add("version", "1.0");

        P("Second example:");
        P(I.ToString());
        P("");

        P("I[\"data\"][0]            : " + I["data"][0]);
        P("I[\"data\"][0].ToString() : " + I["data"][0].ToString());
        P("I[\"data\"][0].Value      : " + I["data"][0].Value);
        P (I.ToString());
    }
コード例 #49
0
    public void SavePlayerLocation()
    {
        JSONClass playerLocation = new JSONClass ();
        GameObject player = GameObject.FindGameObjectWithTag ("Player");

        playerLocation["Coordinates"][-1] = player.transform.position.x.ToString();
        playerLocation["Coordinates"][-1] = player.transform.position.y.ToString();
        playerLocation["Coordinates"][-1] = player.transform.position.z.ToString();

        PlayerPrefs.SetString ("SaveLocation", playerLocation.ToString());
        return;
    }
コード例 #50
0
    //! Saves player data as json string to PlayerPrefs \todo pseudo code -> code
    public void SavePlayerInventory(List <InventoryItem> inputInventory)
    {
        //create new list that will be saved to store the recieved list
        List <InventoryItem> inventorySave = new List <InventoryItem>();
        inventorySave = inputInventory;

        //if the inventory list is empty return
        if(inventorySave == null)
        {
            return;
        }

        //create jsonclass to store the inventory into
        JSONClass inventoryJsonNode = new JSONClass();
        int temp_count = 0;
        //iterate through each item and add its contents to the jsonclass
        foreach(InventoryItem item in inventorySave)
        {
            //saves out the inventory in order the setter functions appear in the inventory item script
            inventoryJsonNode["Inventory"][item.GetItemName()][0] = item.GetItemName();
            inventoryJsonNode["Inventory"][item.GetItemName()][1] = item.GetItemType().ToString();
            inventoryJsonNode["Inventory"][item.GetItemName()][2] = item.GetItemDescription();
            inventoryJsonNode["Inventory"][item.GetItemName()][3] = item.GetItemValue().ToString();
            inventoryJsonNode["Inventory"][item.GetItemName()][4] = item.GetItemAmount().ToString();
            inventoryJsonNode["Inventory"][item.GetItemName()][5] = item.GetItemID().ToString();

            temp_count++;
        }

        //save the inventory to the playerprefs
        PlayerPrefs.SetString("PlayerInventory", inventoryJsonNode.ToString());
        Debug.Log ("Inventory saved!");
    }
コード例 #51
0
    public IEnumerator writeWeaponStats(int id, int damage, int ammo, float rate, int kills)
    {
        JSONClass root = new JSONClass();
        JSONClass weapon = new JSONClass();

        weapon.Add("weapon_id", "" + id);
        weapon.Add("damage", "" + damage);
        weapon.Add("ammo", "" + ammo);
        weapon.Add("fire_rate", "" + rate);
        weapon.Add("kill_count", "" + kills);
        root.Add("weapon_params", weapon);

        Debug.Log(root.ToString());
        byte[] data = Encoding.UTF8.GetBytes(root.ToString());
        WWW www = new WWW(ROOT_URL + POST_WEAPON_URL, data);

        yield return WaitForRequest(www);
    }
コード例 #52
0
        // My facebook feed.
        internal void MyProfile()
        {
            String name = null;
            String id = null;
            var fb = new FacebookClient(GlobalContext.FacebookAccessToken);
            fb.GetCompleted +=
                (o, ex) =>
                {

                    var feed = (IDictionary<String, object>)ex.GetResultData();
                    name = feed["name"].ToString();
                    id = feed["id"].ToString();
                    DBManager.getInstance().saveData(DBManager.DB_Profile, feed);
                    var fbprofiledata = DBManager.getInstance().getDBData(DBManager.DB_Profile);
                    JSONNode jsonObj = JSON.Parse(fbprofiledata);
                    GlobalContext.localUsername = jsonObj["name"].ToString().Split(new char[] { ' ' })[0].Substring(1);
                    GlobalContext.UserFacebookId = id;
                    GlobalContext.GameRoomId = "";
                    JSONNode AuthObj = new JSONClass();
                    AuthObj.Add("FacebookId", id);
                    AuthObj.Add("AccessToken", GlobalContext.FacebookAccessToken);
                    String authString = AuthObj.ToString();
                    Deployment.Current.Dispatcher.BeginInvoke(delegate()
                    {
                        messageGrid.Visibility = Visibility.Visible;
                        WarpClient.GetInstance().Connect(GlobalContext.localUsername, authString);
                    });
                };

            var parameters = new Dictionary<String, object>();
            parameters["fields"] = "id,name";
            fb.GetAsync("me", parameters);
        }
コード例 #53
0
ファイル: GameData.cs プロジェクト: grudin/team-purin
	//it's static so we can call it from anywhere
	public void Save() {
		Debug.Log ("SAVING");
		JSONClass newSave = new JSONClass();
		JSONArray itemSave = new JSONArray ();
		JSONArray runeSave = new JSONArray ();
		newSave.Add ("item", itemSave);
		newSave.Add ("rune", runeSave);
		newSave.Add ("discovered", new JSONData (discovered));
		for (int i = 0; i < itemUnlock.Length; i++) {
			newSave ["item"].Add(new JSONData(itemUnlock[i]));
		}
		for (int i = 0; i < runeUnlock.Length; i++) {
			newSave ["rune"].Add(new JSONData(runeUnlock[i]));
		}
		//Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
		FileStream file = File.Create (Application.persistentDataPath + "/savedData.json"); //you can call it anything you want
		file.Close();
		System.IO.File.WriteAllText(Application.persistentDataPath + "/savedData.json", newSave.ToString(""));
	}   
コード例 #54
0
 void sensor_to_json()
 {
     var I = new JSONClass ();
     I["pitch"].AsDouble = pitch;
     I["yaw"].AsDouble = yaw;
     I["roll"].AsDouble = roll;
     writeSocket(I.ToString());
 }
コード例 #55
0
	void Update() {
		if (dummyMessageTimer >= 0) {
			if(Mathf.Abs(dummyMessageTimer - Time.time) >= 0.3f) {
				string msgJson = "MESG{\"channel_id\": \"0\", \"message\": \"Dummy Text on Editor Mode - " + Time.time + "\", \"user\": {\"image\": \"http://url\", \"name\": \"Sender\"}, \"ts\": 1418979273365, \"scrap_id\": \"\"}";
				_OnMessageReceived(msgJson);
				dummyMessageTimer = Time.time;
			}
		}

		if (dummyChannelListFlag1) {
			dummyChannelListFlag1 = false;
			JSONClass root = new JSONClass();

			JSONArray channels = new JSONArray();
			JSONClass channel = new JSONClass();

			channel.Add ("id", new JSONData(1));
			channel.Add ("channel_url", new JSONData("app_prefix.channel_url"));
			channel.Add ("name", new JSONData("Sample"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(2));
			channel.Add ("channel_url", new JSONData("app_prefix.Unity3d"));
			channel.Add ("name", new JSONData("Unity3d"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(3));
			channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
			channel.Add ("name", new JSONData("Lobby"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(4));
			channel.Add ("channel_url", new JSONData("app_prefix.Cocos2d"));
			channel.Add ("name", new JSONData("Cocos2d"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(5));
			channel.Add ("channel_url", new JSONData("app_prefix.GameInsight"));
			channel.Add ("name", new JSONData("GameInsight"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			root.Add ("has_next", new JSONData(true));
			root.Add ("channels", channels);

			_OnQueryChannelList(root.ToString());
		}

		if (dummyChannelListFlag2) {
			dummyChannelListFlag2 = false;
			JSONClass root = new JSONClass();
			
			JSONArray channels = new JSONArray();
			JSONClass channel = new JSONClass();

			channel.Add ("id", new JSONData(6));
			channel.Add ("channel_url", new JSONData("app_prefix.iOS"));
			channel.Add ("name", new JSONData("iOS"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());
			
			channel.Add ("id", new JSONData(7));
			channel.Add ("channel_url", new JSONData("app_prefix.Android"));
			channel.Add ("name", new JSONData("Android"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(8));
			channel.Add ("channel_url", new JSONData("app_prefix.News"));
			channel.Add ("name", new JSONData("News"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(9));
			channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
			channel.Add ("name", new JSONData("Lobby"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			channel.Add ("id", new JSONData(10));
			channel.Add ("channel_url", new JSONData("app_prefix.iPad"));
			channel.Add ("name", new JSONData("iPad"));
			channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
			channel.Add ("member_count", new JSONData(999));
			channels.Add(channel.ToString());

			root.Add ("has_next", new JSONData(false));
			root.Add ("channels", channels);
			
			_OnQueryChannelList(root.ToString());
		}
	}
コード例 #56
0
    public IEnumerator writePlayerPrefs()
    {
        JSONClass root = new JSONClass();
        JSONClass users = new JSONClass();
        JSONClass wep = new JSONClass();
        JSONClass wep2 = new JSONClass();
        JSONArray weapons = new JSONArray();
        users.Add("user_id", ""+ PlayerPrefs.GetInt("user_id"));
        users.Add("total_kills", ""+ PlayerPrefs.GetInt("total_kills"));
        users.Add("total_points", ""+ PlayerPrefs.GetInt("total_points"));
        users.Add("red", "" + PlayerPrefs.GetFloat("BaseRed"));
        users.Add("green", "" + PlayerPrefs.GetFloat("BaseGreen"));
        users.Add("blue", "" + PlayerPrefs.GetFloat("BaseBlue"));
        users.Add("highest_round_reached", "" + PlayerPrefs.GetInt("highestRound"));
        users.Add("points_available", "" + PlayerPrefs.GetInt("points_available"));
        root.Add("user_params", users);

        Debug.Log(root.ToString());
        byte[] data = Encoding.UTF8.GetBytes(root.ToString());
        WWW www = new WWW(ROOT_URL + POST_USER_URL, data);
           yield return WaitForRequest(www);
    }