public static string toJSON(object obj) { if(obj is string) { JSONString jstring = new JSONString(); jstring.type = "JSONstring"; jstring.message = (string)obj; } return Serialize(obj); }
public override bool Equals(object obj) { if (base.Equals(obj)) { return(true); } string s = obj as string; if (s != null) { return(m_Data == s); } JSONString s2 = obj as JSONString; if (s2 != null) { return(m_Data == s2.m_Data); } return(false); }
public JSONObject CreateNewCharacterSave(string charUID, string charName) { var newCharOBJ = new JSONObject(); modConfig["characters"][-1] = newCharOBJ; // Start adding default values to new character's JSONObject var jsonCharUID = new JSONString(charUID); var jsonCharName = new JSONString(charName); var jsonFirstBarIDs = new JSONArray(); jsonFirstBarIDs[0] = 0; jsonFirstBarIDs[1] = 0; jsonFirstBarIDs[2] = 0; jsonFirstBarIDs[3] = 0; jsonFirstBarIDs[4] = 0; jsonFirstBarIDs[5] = 0; jsonFirstBarIDs[6] = 0; jsonFirstBarIDs[7] = 0; var jsonSecondBarIDs = new JSONArray(); jsonSecondBarIDs[0] = 0; jsonSecondBarIDs[1] = 0; jsonSecondBarIDs[2] = 0; jsonSecondBarIDs[3] = 0; jsonSecondBarIDs[4] = 0; jsonSecondBarIDs[5] = 0; jsonSecondBarIDs[6] = 0; jsonSecondBarIDs[7] = 0; // Now we begin assigning these values to the newly created JSONObject newCharOBJ.Add("characterUID", jsonCharUID); newCharOBJ.Add("characterName", jsonCharName); newCharOBJ.Add("FirstBarIDs", jsonFirstBarIDs); newCharOBJ.Add("SecondBarIDs", jsonSecondBarIDs); return(newCharOBJ); }
public object parsedValue() { if (type == "boolean") { return value == "true" ? true : false; } else if (type == "number") { return float.Parse(value, CultureInfo.InvariantCulture); } else if (type == "string") { return JSON.JsonHelper.Deserialize<string>(value); } else { var jsonString = new JSONString(); jsonString.contents = value; // System.Diagnostics.Debug.WriteLine("\njsonString type for " + (string)value + " is: " + jsonString.GetType() + "\n"); return jsonString; } }
public object parsedValue() { if (type == "boolean") { return(value == "true" ? true : false); } else if (type == "number") { return(float.Parse(value, CultureInfo.InvariantCulture)); } else if (type == "string") { return(JSON.JsonHelper.Deserialize <string>(value)); } else { var jsonString = new JSONString(); jsonString.contents = value; // System.Diagnostics.Debug.WriteLine("\njsonString type for " + (string)value + " is: " + jsonString.GetType() + "\n"); return(jsonString); } }
public static JSONNode Copy(JSONNode node) { JSONNode result = null; if (node.IsBoolean) { result = new JSONBool(false); } if (node.IsNumber) { result = new JSONNumber(0); } if (node.IsString) { result = new JSONString(string.Empty); } if (node.IsNull) { result = JSONNull.CreateOrGet(); } if (node.IsArray) { result = new JSONArray(); foreach (var arrayItem in node) { result.Add(Copy(arrayItem)); } } if (node.IsObject) { result = new JSONObject(); foreach (var field in node) { result.Add(field.Key, Copy(field)); } } return(result); }
/** * Encodes an object into a string, correctly identifying the type */ public static string encode(object value, int indentLevel, JSONStringifyOptions options) { // Decides what it is if (JSONArray.matchesValue(value)) { return(new JSONArray(value).ToString(indentLevel, options)); } else if (JSONString.matchesValue(value)) { return(new JSONString(value).ToString(indentLevel, options)); } else if (JSONNumber.matchesValue(value)) { return(new JSONNumber(value).ToString(indentLevel, options)); } else if (JSONLiteral.matchesValue(value)) { return(new JSONLiteral(value).ToString(indentLevel, options)); } else { return(new JSONObject(value).ToString(indentLevel, options)); } }
// note for textmeshPro //TMPro.TMP_InputField textMeshProReference; #region Methods IEnumerator DoLogin(string _user, string _password) { //the url string createUserURL = "http://localhost:81/nsirpg/Login.php"; WWWForm form = new WWWForm(); form.AddField("username", _user); form.AddField("password", _password); UnityWebRequest webRequest = UnityWebRequest.Post(createUserURL, form); yield return(webRequest.SendWebRequest()); s = webRequest.downloadHandler.text; Debug.Log(s); JSONString js = JSON.Parse(s) as JSONString; if (js == "c") { SceneManager.LoadScene(1); } }
public void TestValues() { int int_const = 1234; JSON int_json = int_const; int int_value = int_json; Assert.IsTrue(int_json.GetJSONType() == JSONType.Value); Assert.IsTrue(int_json.AsValue().GetValueType() == JSONValueType.Int); Assert.IsTrue(int_json.AsValue().ToInt() == int_const); Assert.IsTrue(int_json == int_const); Assert.IsTrue(int_json == int_value); long long_const = (long)int.MaxValue + 1; JSON long_json = long_const; long long_value = long_json; Assert.IsTrue(long_json.GetJSONType() == JSONType.Value); Assert.IsTrue(long_json.AsValue().GetValueType() == JSONValueType.Long); Assert.IsTrue(long_json.AsValue().ToLong() == long_const); Assert.IsTrue(long_json == long_const); Assert.IsTrue(long_json == long_value); float float_const = 0.0f; JSON float_json = float_const; float float_value = float_json; Assert.IsTrue(float_json.GetJSONType() == JSONType.Value); Assert.IsTrue(float_json.AsValue().GetValueType() == JSONValueType.Float); Assert.IsTrue(float_json.AsValue().ToFloat() == float_const); Assert.IsTrue(float_json == float_const); Assert.IsTrue(float_json == float_value); string string_const = "this is a string"; JSON string_json = string_const; string string_value = string_json; Assert.IsTrue(string_json.GetJSONType() == JSONType.Value); Assert.IsTrue(string_json.AsValue().GetValueType() == JSONValueType.String); Assert.IsTrue(string_json.AsValue().ToString() == string_const); Assert.IsTrue(string_json == string_const); Assert.IsTrue(string_json == string_value); bool bool_const = false; JSON bool_json = bool_const; bool bool_value = bool_json; Assert.IsTrue(bool_json.GetJSONType() == JSONType.Value); Assert.IsTrue(bool_json.AsValue().GetValueType() == JSONValueType.Bool); Assert.IsTrue(bool_json.AsValue().ToBool() == bool_const); Assert.IsTrue(bool_json == bool_const); Assert.IsTrue(bool_json == bool_value); var values = new JSONObject(); { JSON item = 1; JSONInt explicitItem = 1; JSONInt created = new JSONInt(1); var assignedInt = new JSONInt().SetInt(1); var assignedLong = new JSONInt().SetLong(1L); var assignedfloat = new JSONInt().SetFloat(1f); var assignedBool = new JSONInt().SetBool(true); var assignedString = new JSONInt().SetString("1"); JSON array = new JSONArray { 1, item, explicitItem, created, assignedInt, assignedLong, assignedfloat, assignedBool, assignedString }; values["Int"] = array; } { JSON item = 1L; JSONLong explicitItem = 1L; JSONLong created = new JSONLong(1L); var assignedInt = new JSONLong().SetInt(1); var assignedLong = new JSONLong().SetLong(1L); var assignedfloat = new JSONLong().SetFloat(1f); var assignedBool = new JSONLong().SetBool(true); var assignedString = new JSONLong().SetString("1"); JSON array = new JSONArray { 1L, item, explicitItem, created, assignedInt, assignedLong, assignedfloat, assignedBool, assignedString }; values["Long"] = array; } { JSON item = 1f; JSONFloat explicitItem = 1f; JSONFloat created = new JSONFloat(1f); var assignedInt = new JSONFloat().SetInt(1); var assignedLong = new JSONFloat().SetLong(1L); var assignedfloat = new JSONFloat().SetFloat(1f); var assignedBool = new JSONFloat().SetBool(true); var assignedString = new JSONFloat().SetString("1"); JSON array = new JSONArray { 1f, item, explicitItem, created, assignedInt, assignedLong, assignedfloat, assignedBool, assignedString }; values["Float"] = array; } { JSON item = true; JSONBool explicitItem = true; JSONBool created = new JSONBool(true); var assignedInt = new JSONBool().SetInt(1); var assignedLong = new JSONBool().SetLong(1L); var assignedfloat = new JSONBool().SetFloat(1f); var assignedBool = new JSONBool().SetBool(true); var assignedString = new JSONBool().SetString("true"); JSON array = new JSONArray { true, item, explicitItem, created, assignedInt, assignedLong, assignedfloat, assignedBool, assignedString }; values["Bool"] = array; } { JSON item = "1"; JSONString explicitItem = "1"; JSONString created = new JSONString("1"); var assignedInt = new JSONString().SetInt(1); var assignedLong = new JSONString().SetLong(1L); var assignedfloat = new JSONString().SetFloat(1f); var assignedBool = new JSONString().SetBool(true); var assignedString = new JSONString().SetString("1"); JSON array = new JSONArray { "1", item, explicitItem, created, assignedInt, assignedLong, assignedfloat, assignedBool, assignedString }; values["String"] = array; } foreach (var kvp in values) { for (int i = 0; i < kvp.Value.Count - 1; ++i) { var a = kvp.Value[i]; var b = kvp.Value[i + 1]; var equal = a == b; if (kvp.Key == "String") { if ((a == "true" && b == "1") || (a == "1" && b == "true")) { equal = true; } } Assert.IsTrue(equal); } } }
private async Task OnContext(HttpListenerContext ctx) { string[] resource_file_list = { "/Statics/Css/default.css", "/Statics/Css/Material+Icons.css", "/Statics/Css/materialize.min.css", "/Statics/Fonts/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2", "/Statics/Js/default.js", "/Statics/Js/materialize.min.js", "/Statics/Js/jquery-3.5.1.min.js", "/Statics/Lang/en.json", "/Statics/Lang/zh.json", "/Statics/Lang/ja.json" }; await _requestLock.WaitAsync(); try { var request = ctx.Request; var response = ctx.Response; if (request.HttpMethod == "POST" && request.Url.AbsolutePath == "/submit") { await Submit(request, response).ConfigureAwait(false); } else if (request.HttpMethod == "GET" && Array.IndexOf(resource_file_list, request.Url.AbsolutePath) > -1) { // Load resources response.StatusCode = 200; var Ext = Path.GetExtension(request.Url.AbsolutePath); if (Ext == ".html") { response.ContentType = "text/html"; } else if (Ext == ".css") { response.ContentType = "text/css"; } else if (Ext == ".js") { response.ContentType = "application/javascript"; } else if (Ext == ".json") { response.ContentType = "application/json"; } else if (Ext == ".woff2") { response.ContentType = "font/woff2"; } Console.WriteLine("Trying to get resource: " + "ChatCore.Resources.Web" + request.Url.AbsolutePath.Replace("/", ".")); var buffer = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("ChatCore.Resources.Web" + request.Url.AbsolutePath.Replace("/", ".")) !); buffer.BaseStream.CopyTo(response.OutputStream); } else { var settingsJson = _settings.GetSettingsAsJson(); settingsJson["twitch_oauth_token"] = new JSONString(_authManager.Credentials.Twitch_OAuthToken); settingsJson["twitch_channels"] = new JSONArray(_authManager.Credentials.Twitch_Channels); var pageBuilder = new StringBuilder(_pageData); pageBuilder.Replace("{libVersion}", ChatCoreInstance.Version.ToString(3)); pageBuilder.Replace("var data = {};", $"var data = {settingsJson};"); var data = Encoding.UTF8.GetBytes(pageBuilder.ToString()); response.ContentType = "text/html"; response.ContentEncoding = Encoding.UTF8; response.ContentLength64 = data.LongLength; await response.OutputStream.WriteAsync(data, 0, data.Length); } response.Close(); } catch (Exception ex) { _logger.LogError(ex, "Exception occurred during webapp request."); } finally { _requestLock.Release(); } }
public JSONReader (string _inputJSONString) { JSONString = new JSONString(_inputJSONString); }
private static void SendMessageLoop() { while (!Globals.IsApplicationExiting) { Thread.Sleep(500); if (_sendQueue.Count > 0 && _sendQueue.TryPeek(out var messageToSend)) { try { HttpWebRequest web = (HttpWebRequest)WebRequest.Create($"https://www.googleapis.com/youtube/v3/liveChat/messages?part=snippet"); web.Method = "POST"; web.Headers.Add("Authorization", $"{YouTubeOAuthToken.tokenType} {YouTubeOAuthToken.accessToken}"); web.ContentType = "application/json"; JSONObject container = new JSONObject(); container["snippet"] = new JSONObject(); container["snippet"]["liveChatId"] = new JSONString(YouTubeLiveBroadcast.currentBroadcast.snippet.liveChatId); container["snippet"]["type"] = new JSONString("textMessageEvent"); container["snippet"]["textMessageDetails"] = new JSONObject(); container["snippet"]["textMessageDetails"]["messageText"] = new JSONString(messageToSend.Value); string snippetString = container.ToString(); Plugin.Log($"Sending {snippetString}"); var postData = Encoding.ASCII.GetBytes(snippetString); web.ContentLength = postData.Length; using (var stream = web.GetRequestStream()) stream.Write(postData, 0, postData.Length); using (HttpWebResponse resp = (HttpWebResponse)web.GetResponse()) { if (resp.StatusCode != HttpStatusCode.OK) { using (Stream dataStream = resp.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { var response = reader.ReadToEnd(); Plugin.Log($"Status: {resp.StatusCode} ({resp.StatusDescription}), Response: {response}"); continue; } } } using (Stream dataStream = resp.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { // Read the response into a JSON objecet var json = JSON.Parse(reader.ReadToEnd()).AsObject; // Then create a new YouTubeMessage object from it and send it along to the other StreamCore clients, excluding the assembly that sent the message var newMessage = new YouTubeMessage(); newMessage.Update(json); var assemblyHash = messageToSend.Key.ToString(); // Invoke YouTube message received callbacks YouTubeMessageHandlers.InvokeHandler(newMessage, assemblyHash); _sendQueue.TryDequeue(out var gone); } } } } catch (ThreadAbortException ex) { return; } catch (Exception ex) { // Failed the send the message for some other reason, it will be retried next iteration Plugin.Log($"Failed to send YouTube message, trying again in a few seconds! {ex.ToString()}"); Thread.Sleep(2500); } } } }
private static void CreateCommands() { comands.Add("DANMU_MSG", (b, danmuku) => { b.MessageType = "danmuku"; var info = danmuku["info"].AsArray !; b.Uid = info[2][0].AsInt; b.Username = info[2][1].Value; b.Content = info[1].Value.ToString(); b.Message = info[1].Value; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); //b.Channel = new BiliBiliChatChannel(danmuku); }); comands.Add("DANMU_MSG:4:0:2:2:2:0", (b, danmuku) => { b.MessageType = "danmuku"; var info = danmuku["info"].AsArray !; b.Uid = info[2][0].AsInt; b.Username = info[2][1].Value; b.Content = info[1].Value.ToString(); b.Message = info[1].Value; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); //b.Channel = new BiliBiliChatChannel(danmuku); }); comands.Add("SEND_GIFT", (b, danmuku) => { b.MessageType = "gift"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["uname"].Value; b.Content = ""; b.IsHighlighted = true; var info = new JSONArray(); info[2] = new JSONObject(); info[7] = new JSONNumber(data["medal_info"]["guard_level"].AsInt); info[2][0] = new JSONNumber(b.Uid); info[2][1] = new JSONString(b.Username); info[2][2] = new JSONNumber(0); info[2][7] = new JSONString(""); info[2][3] = new JSONArray(); info[2][3][0] = new JSONNumber(data["medal_info"]["medal_level"].AsInt); info[2][3][1] = new JSONNumber(data["medal_info"]["medal_name"].Value); if (string.IsNullOrEmpty(data["combo_num"].Value)) { b.Message = data["action"].Value + data["num"].Value + "个" + data["giftName"].Value; } else { b.Message = data["action"].Value + data["num"].Value + "个" + data["giftName"].Value + " x" + data["combo_num"].Value; } b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); }); comands.Add("COMBO_END", (b, danmuku) => { b.MessageType = "combo_end"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["uname"].Value; b.Content = ""; b.IsHighlighted = true; var info = new JSONArray(); info[2] = new JSONObject(); info[7] = new JSONNumber(data["medal_info"]["guard_level"].AsInt); info[2][0] = new JSONNumber(b.Uid); info[2][1] = new JSONString(b.Username); info[2][2] = new JSONNumber(0); info[2][7] = new JSONString(""); info[2][3] = new JSONArray(); info[2][3][0] = new JSONNumber(data["medal_info"]["medal_level"].AsInt); info[2][3][1] = new JSONNumber(data["medal_info"]["medal_name"].Value); b.Message = data["action"].Value + (data["gift_num"].AsInt == 0 ? 1 : data["gift_num"].AsInt) + "个" + data["gift_name"].Value + " x" + data["combo_num"].Value; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); }); comands.Add("COMBO_SEND", (b, danmuku) => { b.MessageType = "combo_send"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["uname"].Value; b.Content = ""; b.IsHighlighted = true; var info = new JSONArray(); info[2] = new JSONObject(); info[7] = new JSONNumber(data["medal_info"]["guard_level"].AsInt); info[2][0] = new JSONNumber(b.Uid); info[2][1] = new JSONString(b.Username); info[2][2] = new JSONNumber(0); info[2][7] = new JSONString(""); info[2][3] = new JSONArray(); info[2][3][0] = new JSONNumber(data["medal_info"]["medal_level"].AsInt); info[2][3][1] = new JSONNumber(data["medal_info"]["medal_name"].Value); b.Message = data["action"].Value + (data["gift_num"].AsInt == 0 ? 1 : data["gift_num"].AsInt) + "个" + data["gift_name"].Value + " x" + data["combo_num"]; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); }); comands.Add("SUPER_CHAT_MESSAGE", (b, danmuku) => { b.MessageType = "super_chat"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["user_info"]["uname"].Value; b.Content = data["message"].Value; b.IsHighlighted = true; var info = new JSONArray(); info[2] = new JSONObject(); info[7] = new JSONNumber(data["user_info"]["guard_level"].AsInt); info[2][0] = new JSONNumber(b.Uid); info[2][1] = new JSONString(b.Username); info[2][2] = new JSONNumber(0); info[2][7] = new JSONString(""); info[2][3] = new JSONArray(); b.Message = "【SC (¥" + data["price"].AsInt + ")】" + b.Content; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); }); comands.Add("SUPER_CHAT_MESSAGE_JPN", (b, danmuku) => { b.MessageType = "super_chat_japanese"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["user_info"]["uname"].Value; b.Content = data["message_jpn"].Value; b.IsHighlighted = true; var info = new JSONArray(); info[2] = new JSONObject(); info[7] = new JSONNumber(data["user_info"]["guard_level"].AsInt); info[2][0] = new JSONNumber(b.Uid); info[2][1] = new JSONString(b.Username); info[2][2] = new JSONNumber(0); info[2][7] = new JSONString(""); info[2][3] = new JSONArray(); b.Message = "【SC (JP¥" + data["price"].AsInt + ")】" + b.Content; b.Sender = new BiliBiliChatUser(info, danmuku["room_id"]); }); comands.Add("WELCOME", (b, danmuku) => { b.MessageType = "welcome"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["uname"].Value; b.Content = ""; b.IsSystemMessage = true; b.Message = "欢迎老爷 " + b.Username + " 进入直播间"; }); comands.Add("INTERACT_WORD", (b, danmuku) => { var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["uname"].Value; b.Content = ""; b.IsSystemMessage = true; switch (data["msg_type"].Value.ToString()) { case "1": b.MessageType = "welcome"; b.Message = "欢迎 " + b.Username + " 进入直播间"; break; case "2": b.MessageType = "follow"; b.Message = "感谢 " + b.Username + " 关注直播间"; break; case "3": b.MessageType = "share"; b.Message = "感谢 " + b.Username + " 分享直播间"; break; case "4": b.MessageType = "special_follow"; b.Message = "感谢 " + b.Username + " 特别关注"; break; case "5": b.MessageType = "mutual_follow"; b.Message = "感谢 " + b.Username + " 相互关注"; break; case "6": b.MessageType = "unknown"; b.Message = "【暂不支持该消息】"; break; } }); comands.Add("WELCOME_GUARD", (b, danmuku) => { b.MessageType = "welcome_guard"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["username"].Value; b.Content = ""; b.IsSystemMessage = true; b.IsHighlighted = true; b.Message = "欢迎舰长 " + b.Username + " 进入直播间"; }); comands.Add("ENTRY_EFFECT", (b, danmuku) => { b.MessageType = "effect"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["copy_writing"].Value.Replace("<%", "").Replace("%>", ""); b.Content = data["copy_writing"].Value.Replace("<%", "").Replace("%>", ""); b.IsSystemMessage = true; b.Message = b.Content; }); comands.Add("ROOM_RANK", (b, danmuku) => { b.MessageType = "global"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【打榜】" + data["rank_desc"].Value; }); comands.Add("ROOM_BANNER", (b, danmuku) => { b.MessageType = "global"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【打榜】" + (string.IsNullOrEmpty(data["bls_rank_info"]["rank_info"]["title"].Value)? "小时榜" : data["bls_rank_info"]["rank_info"]["title"].Value + "-" + data["bls_rank_info"]["team_name"].Value) + " 排名: " + data["bls_rank_info"]["rank_info"]["rank_info"]["rank"].Value; }); comands.Add("ACTIVITY_BANNER_UPDATE_V2", (b, danmuku) => { b.MessageType = "global"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【横幅】当前分区排名" + data["title"].Value; }); comands.Add("ONLINERANK", (b, danmuku) => { b.MessageType = "global"; var data = danmuku["data"].AsObject !; /*var online_rank = data["list"].AsArray;*/ b.IsSystemMessage = true; b.Message = "【在线排名】当前分区排名" + data["title"].Value; }); comands.Add("ROOM_REAL_TIME_MESSAGE_UPDATE", (b, danmuku) => { b.MessageType = "global"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【关注】粉丝数" + data["fans"].Value.ToString(); }); comands.Add("NOTICE_MSG", (b, danmuku) => { b.MessageType = "junk"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【喇叭】" + data["msg_common"].Value; }); comands.Add("ANCHOR_LOT_START", (b, danmuku) => { b.MessageType = "anchor_lot_start"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【天选】天选之子活动开始啦!" + data["require_text"].Value + "赢得" + data["award_name"].Value; }); comands.Add("ANCHOR_LOT_CHECKSTATUS", (b, danmuku) => { b.MessageType = "anchor_lot_checkstatus"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【天选】天选之子活动开始啦!"; }); comands.Add("ANCHOR_LOT_END", (b, danmuku) => { b.MessageType = "anchor_lot_end"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【天选】天选之子活动结束啦!"; }); comands.Add("ANCHOR_LOT_AWARD", (b, danmuku) => { b.MessageType = "anchor_lot"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; var list = data["award_users"].AsArray !; var usernameList = ""; foreach (var item in list) { usernameList += (item.Value)["uname"].Value.ToString(); } b.Message = "【天选】恭喜" + usernameList + "获得" + data["award_name"].Value; }); comands.Add("RAFFLE_START", (b, danmuku) => { b.MessageType = "raffle_start"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【抽奖】" + data["title"].Value + "开始啦!"; }); comands.Add("ROOM_BLOCK_MSG", (b, danmuku) => { b.MessageType = "blocklist"; var data = danmuku["data"].AsObject !; b.IsSystemMessage = true; b.Message = "【封禁】" + data["uname"].Value + "(UID: " + data["uid"].Value + ")"; }); comands.Add("GUARD_BUY", (b, danmuku) => { b.MessageType = "new_guard"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["username"].Value; b.Content = ""; b.IsHighlighted = true; b.Message = "感谢 " + b.Username + " 成为 " + data["gift_name"].Value + " 加入舰队~"; }); comands.Add("USER_TOAST_MSG", (b, danmuku) => { b.MessageType = "new_guard_msg"; var data = danmuku["data"].AsObject !; b.Uid = data["uid"].AsInt; b.Username = data["username"].Value; b.Content = ""; b.IsSystemMessage = true; b.IsHighlighted = true; b.Message = b.Username + " 开通了 " + data["num"].Value + "个" + data["unit"] + "的" + data["role_name"] + " 进入舰队啦"; }); comands.Add("GUARD_MSG", (b, danmuku) => { var data = danmuku["data"].AsObject !; var broadcast_type = danmuku["broadcast_type"].Value; if (broadcast_type != "0") { b.MessageType = "guard_msg"; b.Message = "【上舰】" + data["msg"].Value.Replace(":?", ""); } else { b.MessageType = "junk"; b.Message = "【上舰广播】" + data["msg"].Value.Replace(":?", ""); } b.IsSystemMessage = true; }); comands.Add("GUARD_LOTTERY_START", (b, danmuku) => { b.MessageType = "guard_lottery_msg"; b.IsSystemMessage = true; b.Message = "【抽奖】上舰抽奖开始啦"; }); comands.Add("ROOM_CHANGE", (b, danmuku) => { var data = danmuku["data"].AsObject !; b.MessageType = "room_change"; b.IsSystemMessage = true; b.Message = "【变更】直播间名称为: " + data["title"].Value; }); comands.Add("PREPARING", (b, danmuku) => { b.MessageType = "room_preparing"; b.IsSystemMessage = true; b.Message = "【下播】直播间准备中"; }); comands.Add("LIVE", (b, danmuku) => { b.MessageType = "room_live"; b.IsSystemMessage = true; b.Message = "【开播】直播间开播啦"; }); comands.Add("WARNING", (b, danmuku) => { b.MessageType = "warning"; b.IsHighlighted = true; b.Message = "【超管】" + danmuku["msg"]?.Value; }); comands.Add("CUT_OFF", (b, danmuku) => { b.MessageType = "cut_off"; b.IsHighlighted = true; b.Message = "【切断】" + danmuku["msg"]?.Value; }); comands.Add("STOP_LIVE_ROOM_LIST", (b, danmuku) => { var data = danmuku["data"].AsObject !; b.MessageType = "junk"; b.IsSystemMessage = true; b.Message = "以下房间停止直播:" + data["room_id_list"].AsArray !.ToString(); });
private JSONString ParseString() { db("parsing string"); JSONString ret = new JSONString(); parseChar('"', true, false); bool slashed = false; int start = ptr; int length = 0; while(!(tok() == '"' && !slashed)) { if(tok() == '\\' && !slashed) slashed = true; else slashed = false; lex(); length++; } ret.val = data.Substring(start, length); parseChar('"', false, true); return ret; }
private void ChangeType(object sender, EventArgs e) { ComboBox c = (ComboBox)sender; JSONNode n = (JSONNode)c.Tag; TreeNode t = JSONFormUtil.FindTreeNode(tview_object.TopNode, n); JSONNode newnode; switch (c.SelectedIndex) { case 0: newnode = new JSONArray(); break; case 1: newnode = new JSONBool(true); break; case 2: newnode = new JSONNull(); break; case 3: newnode = new JSONNumber(0); break; case 4: newnode = new JSONObject(); break; case 5: newnode = new JSONString("type a string"); break; default: newnode = new JSONNull(); break; } t.Nodes.Clear(); t.Text = newnode.type.GetTypeString(); t.Tag = newnode; JSONNode pNode = n.parent; for (int i = 0; i < pNode.Count; ++i) { if (ReferenceEquals(pNode[i], n)) { pNode[i] = newnode; break; } } Panel p = (Panel)c.Parent; p.Tag = newnode; Control keybox = FindControl(p, "keybox"); string original_key = keybox.Text; bool original_fixed = keybox.Enabled; p.Controls.Clear(); p.Controls.Add(CreateKeyBox(newnode, original_key, original_fixed)); p.Controls.Add(CreateComboBox(newnode)); p.Controls.Add(CreateDeleteButton(newnode)); if (newnode.type == JSONType.Object || newnode.type == JSONType.Array) { p.Controls.Add(CreateValueLabel()); p.Controls.Add(CreateModifyButton(newnode)); Panel g = CreateJSONNodeGroupBox(newnode, p); p.Controls.Add(CreateNewNodeButton(newnode)); g.BackColor = FormConstValue.baseColor; g.Location = new Point(FormConstValue.stepX, FormConstValue.stepY); p.Controls.Add(g); } else { p.Controls.Add(CreateValueTextBox(newnode)); } PanelReSort(p); }
// ================================================================================================================ // INTERNAL INTERFACE --------------------------------------------------------------------------------------------- protected override void parseValueFromInput() { ParsingState parsingState = ParsingState.Start; char c; int i = 0; string key = "undefined"; JSONValue valueObject; value = new Dictionary <string, object>(); while (i < input.Length && parsingState != ParsingState.End) { c = input.ToString(inputStart + i, 1)[0]; // TODO: is this efficient? switch (parsingState) { case ParsingState.Start: if (c == CHAR_START) { // Starting object parsingState = ParsingState.BeforeKey; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key start"); } break; case ParsingState.BeforeKey: if (!JSONParser.isWhitespace(c)) { if (JSONString.matchesInput(input, inputStart + i)) { // Key starting JSONString keyObject = new JSONString(input, inputStart + i); key = (string)keyObject.getValue(); i += keyObject.getInputLength() - 1; parsingState = ParsingState.AfterKey; } else if (c == CHAR_END) { // Premature end parsingState = ParsingState.End; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key name"); } } break; case ParsingState.AfterKey: if (!JSONParser.isWhitespace(c)) { if (c == CHAR_KEY_SEPARATOR) { parsingState = ParsingState.BeforeValue; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key separator"); } } break; case ParsingState.BeforeValue: if (!JSONParser.isWhitespace(c)) { valueObject = JSONParser.parse(input, inputStart + i); i += valueObject.getInputLength() - 1; value.Add(key, valueObject.getValue()); parsingState = ParsingState.AfterValue; } break; case ParsingState.AfterValue: if (!JSONParser.isWhitespace(c)) { if (c == CHAR_END) { parsingState = ParsingState.End; } else if (c == CHAR_ITEM_SEPARATOR) { parsingState = ParsingState.BeforeKey; } else { Debug.LogError("Invalid character \"" + c + "\" when expecting object key end"); } } break; } i++; } inputLength = i; }
private static JSONNode DoObject2JSONNode(string key, object obj, JSONNode parent) { if (obj == null) { JSONNode jnull = new JSONNull(); if (!DoObject2JSONNode_AddToParent(parent, key, jnull)) { return(jnull); } } else if (obj is IDictionary) { JSONObject jobject = Johny.JSONNodePool.Claim(typeof(Johny.JSONObject)).AsObject; var it = (obj as IDictionary).GetEnumerator(); while (it.MoveNext()) { DoObject2JSONNode(it.Key as string, it.Value, jobject); } if (!DoObject2JSONNode_AddToParent(parent, key, jobject)) { return(jobject); } } else if (obj is ICollection) { JSONArray jarray = Johny.JSONNodePool.Claim(typeof(Johny.JSONArray)).AsArray; var it = (obj as ICollection).GetEnumerator(); while (it.MoveNext()) { DoObject2JSONNode(string.Empty, it.Current, jarray); } if (!DoObject2JSONNode_AddToParent(parent, key, jarray)) { return(jarray); } } else if (obj is string) { JSONString jstring = Johny.JSONNodePool.Claim(typeof(Johny.JSONString)) as JSONString; jstring.InitString(obj as string); if (!DoObject2JSONNode_AddToParent(parent, key, jstring)) { return(jstring); } } else if (obj is bool) { JSONBool jbool = new JSONBool((bool)obj); if (!DoObject2JSONNode_AddToParent(parent, key, jbool)) { return(jbool); } } else if (obj is System.Enum) { JSONNumber jnum = new JSONNumber((int)obj); if (!DoObject2JSONNode_AddToParent(parent, key, jnum)) { return(jnum); } } else if (IsNumeric(obj)) { double dd = Convert.ToDouble(obj); JSONNumber jnum = new JSONNumber(dd); if (!DoObject2JSONNode_AddToParent(parent, key, jnum)) { return(jnum); } } else { EB.Debug.LogError($"此类型JSON无法解析,请自行转换成基本类型!==> {obj.GetType().FullName}"); } return(null); }
public void Deserialize(string json) { var puzzle_entities = new List <PuzzleEntityModel>(); var puzzle_info = JSONString.Parse(json); var puzzle_entity_infos = puzzle_info["puzzle_entities"].AsArray; var command_infos = puzzle_info["commands"].AsArray; var command_group_infos = puzzle_info["command_groups"].AsArray; foreach (JSONObject puzzle_entity_info in puzzle_entity_infos) { var new_puzzle_entity = GameObject.Instantiate(Resources.Load <GameObject>("Prefabs/PuzzleEntities/" + puzzle_entity_info["name"].Value)); new_puzzle_entity.AddComponent <PuzzleEntityModel>().FromJson(puzzle_entity_info); puzzle_entities.Add(new_puzzle_entity.GetComponent <PuzzleEntityModel>()); } List <CommandModel> single_commands = new List <CommandModel>(); foreach (JSONObject command_info in command_infos) { var new_command = GameObject.Instantiate <GameObject>(Resources.Load <GameObject>("Prefabs/Commands/" + command_info["name"].Value)); var single_command = new_command.AddComponent <SingleCommandModel>(); single_command.Playable = puzzle_entities[command_info["playable_entity_id"].AsInt].GetComponent <PlayableModel>(); single_command.FromJson(command_info); single_commands.Add(single_command); } List <CommandModel> command_groups = new List <CommandModel>(); foreach (JSONObject command_group_info in command_group_infos) { var new_command_group = new GameObject(); var command_group = new_command_group.AddComponent <CommandGroupModel>(); int playable_id = command_group_info["playable_entity_id"].AsInt; int conditional_command_id = command_group_info["command_ids"][0].AsInt; command_group.Playable = puzzle_entities[playable_id].GetComponent <PlayableModel>(); command_group.ConditionalCommand = conditional_command_id == -1 ? null : single_commands[conditional_command_id] as SingleCommandModel; command_group.FromJson(command_group_info); command_groups.Add(command_group); } for (int i = 0; i < command_groups.Count; ++i) { var command_ids = command_group_infos[i]["command_ids"].AsArray; for (int j = 1; j < command_ids.Count; ++j) { int id = command_ids[j].AsInt; var commands = id < 0 ? command_groups : single_commands; id = id < 0 ? (id + 1) * -1 : id; var command_group = command_groups[i] as CommandGroupModel; command_group.CommandsSequence.Add(commands[id]); } } var tile_entities = from puzzle_entity in puzzle_entities where puzzle_entity.GetComponent <TileModel>() select puzzle_entity; tiles.Clear(); foreach (var tile_entity in tile_entities) { tiles.Add(convertVector3ToCellNo(tile_entity.transform.position), tile_entity.GetComponent <PuzzleEntityModel>()); var upper_entity = from entity in puzzle_entities where !entity.GetComponent <TileModel>() && entity.transform.position == tile_entity.transform.position + new Vector3(0, 1, 0) select entity; if (upper_entity.Count() == 0) { continue; } tile_entity.GetComponent <TileModel>().PuzzleEntity = upper_entity.ToArray <PuzzleEntityModel>()[0]; } }
public void addStringValue(JSONString key, JSONValue val) { keys[len] = key; vals[len] = val; len++; }
public JSONReader(string _inputJSONString) { JSONString = new JSONString(_inputJSONString); }
public JSONValue get(JSONString key) { for (int i = 0; i < len; i++) { if (key.str == keys[i].str) { return vals[i]; } } return null; }
public JSONObject decodeObject(string str, ref int index) { if (str[index] != '{') { return(null); } index++; JSONObject jo = new JSONObject(); bool object_should_over = false; while (index < str.Length) { JSONString key = null; JSONValue val = null; index = passWhiteSpace(str, index); if (str[index] == '}') { index++; return(jo); } else if (object_should_over) { throw new JSONError(str, index); } if (str[index] == '\'' || str[index] == '\"') { key = decodeString(str, ref index); } if (key == null) { throw new JSONError(str, index); } index = passWhiteSpace(str, index); if (str[index] != ':') { throw new JSONError(str, index); } index++; val = decodeValue(str, ref index); if (val == null) { throw new JSONError(str, index); } jo.addStringValue(key, val); index = passWhiteSpace(str, index); if (str[index] != ',') { object_should_over = true; } else { index++; } } return(null); }
public void Execute(string client, JSONNode args) { var result = new JSONString(BuildInfo.buildVersion); ApiManager.Instance.SendResult(client, result); }
void InitFixturePreview() { JSONObject fixtureDef = FixtureLibrary.Instance.GetFixtureDef(libraryPath); if (fixtureDef == null) { return; } _isLaser = false; foreach (JSONString c in fixtureDef["categories"] as JSONArray) { if (c == "Laser") { _isLaser = true; } } // physical JSONArray lens = fixtureDef["physical"]["lens"]["degreesMinMax"] as JSONArray; if (lens != null && lens[0] == lens[1]) { _beamAngle = lens[0]; } else { _beamAngle = 10; } Vector3 pixelSize = new Vector3(0.05f, 0.05f, 0); JSONArray dimensions = fixtureDef["physical"]["matrixPixels"]["dimensions"] as JSONArray; if (dimensions != null) { pixelSize = new Vector3(dimensions[0], dimensions[1], dimensions[2]) / 1000; } Vector3 pixelSpacing = Vector3.zero; JSONArray spacing = fixtureDef["physical"]["matrixPixels"]["spacing"] as JSONArray; if (spacing != null) { pixelSpacing = new Vector3(spacing[0], spacing[1], spacing[2]) / 1000; } // wheels wheelNames = new List <string>(); wheelData = new List <Wheel>(); if (fixtureDef["wheels"] != null) { foreach (KeyValuePair <string, JSONNode> wheel in fixtureDef["wheels"] as JSONObject) { wheelNames.Add(wheel.Key); wheelData.Add(new Wheel()); } } // pixels isMatrix = false; for (int i = transform.childCount - 1; i >= 0; i--) { Transform child = transform.GetChild(i); if (Application.isPlaying) { Destroy(child.gameObject); } else { DestroyImmediate(child.gameObject); } } if (fixtureDef["matrix"] != null) { JSONArray pixelKeysZ = fixtureDef["matrix"]["pixelKeys"] as JSONArray; if (pixelKeysZ != null) { for (int z = 0; z < pixelKeysZ.Count; z++) { JSONArray pixelKeysY = pixelKeysZ[z] as JSONArray; for (int y = 0; y < pixelKeysY.Count; y++) { JSONArray pixelKeysX = pixelKeysY[y] as JSONArray; for (int x = 0; x < pixelKeysX.Count; x++) { JSONString pixelKey = pixelKeysX[x] as JSONString; if (string.IsNullOrEmpty(pixelKey)) { continue; } GameObject pixel = CreatePixel(pixelKey, pixelSize); // TODO: pixel spacing pixel.transform.localPosition = new Vector3(((pixelKeysX.Count - 1) / 2f - x) * pixelSize.x, ((pixelKeysY.Count - 1) / 2f - y) * pixelSize.y, ((pixelKeysZ.Count - 1) / 2f - z) * pixelSize.z); pixel.transform.SetParent(transform, false); } } } } else { JSONArray pixelCount = fixtureDef["matrix"]["pixelCount"] as JSONArray; for (int z = 0; z < pixelCount[2]; z++) { for (int y = 0; y < pixelCount[1]; y++) { for (int x = 0; x < pixelCount[0]; x++) { string pixelKey = null; if (pixelCount[1] > 1) { if (pixelCount[2] > 1) { pixelKey = string.Format("({0}, {1}, {2})", x + 1, y + 1, z + 1); } else { pixelKey = string.Format("({0}, {1})", x + 1, y + 1); } } else { pixelKey = string.Format("{0}", x + 1); } GameObject pixel = CreatePixel(pixelKey, pixelSize); // TODO: pixel spacing pixel.transform.localPosition = new Vector3(((pixelCount[0] - 1) / 2f - x) * pixelSize.x, ((pixelCount[1] - 1) / 2f - y) * pixelSize.y, ((pixelCount[2] - 1) / 2f - z) * pixelSize.z); pixel.transform.SetParent(transform, false); } } } } pixelGroups = new Dictionary <string, List <string> >(); if (fixtureDef["matrix"]["pixelGroups"] != null) { foreach (KeyValuePair <string, JSONNode> pixelGroup in fixtureDef["matrix"]["pixelGroups"] as JSONObject) { List <string> groupMembers = new List <string>(); foreach (JSONString pixelKey in pixelGroup.Value as JSONArray) { groupMembers.Add(pixelKey); } pixelGroups[pixelGroup.Key] = groupMembers; } } } channelNames = new List <string>(); templateChannelNames = new List <string>(); pixelKeys = new List <string>(); foreach (JSONNode channelRef in fixtureDef["modes"][modeIndex]["channels"] as JSONArray) { // matrix insert block if (channelRef is JSONObject) { // TODO: more repeatFor modes foreach (JSONString pixelKey in channelRef["repeatFor"] as JSONArray) { pixelKeys.Add(pixelKey); foreach (JSONString templateChannelName in channelRef["templateChannels"] as JSONArray) { templateChannelNames.Add(templateChannelName); channelNames.Add(FixtureLibrary.ExpandTemplateChannelName(templateChannelName, pixelKey)); } } } else if (channelRef == null) { channelNames.Add(""); } else { channelNames.Add(channelRef); } } numChannels = channelNames.Count; capabilityNames = new List <string>(); capabilityChannels = new List <int>(); for (int i = 0; i < numChannels; i++) { string channelName = channelNames[i]; string channelKey = FixtureLibrary.ParseTemplateChannelKey(channelName); string channelPixelKey = FixtureLibrary.ParseTemplatePixelKey(channelName); if (!string.IsNullOrEmpty(channelPixelKey)) { isMatrix = true; } JSONObject channel = GetChannelDef(channelKey, channelPixelKey); if (channel == null) { continue; } JSONObject capability = channel["capability"] as JSONObject; if (capability != null) { string capabilityName = capability["type"]; if (capability["type"] == "ColorIntensity") { capabilityName += " " + capability["color"]; } capabilityNames.Add(capabilityName); capabilityChannels.Add(i); } } if (useChannelDefaults) { SetChannelDefaults(); } }