public void DeserializePersonAndGroupByGender_StaticJson_GroupedCats() { string json = "[{\"name\":\"Bob\",\"gender\":\"Male\",\"age\":23,\"pets\":[{\"name\":\"Garfield\",\"type\":\"Cat\"},{\"name\":\"Fido\",\"type\":\"Dog\"}]},{\"name\":\"Jennifer\",\"gender\":\"Female\",\"age\":18,\"pets\":[{\"name\":\"Garfield\",\"type\":\"Cat\"}]},{\"name\":\"Steve\",\"gender\":\"Male\",\"age\":45,\"pets\":null},{\"name\":\"Fred\",\"gender\":\"Male\",\"age\":40,\"pets\":[{\"name\":\"Tom\",\"type\":\"Cat\"},{\"name\":\"Max\",\"type\":\"Cat\"},{\"name\":\"Sam\",\"type\":\"Dog\"},{\"name\":\"Jim\",\"type\":\"Cat\"}]},{\"name\":\"Samantha\",\"gender\":\"Female\",\"age\":40,\"pets\":[{\"name\":\"Tabby\",\"type\":\"Cat\"}]},{\"name\":\"Alice\",\"gender\":\"Female\",\"age\":64,\"pets\":[{\"name\":\"Simba\",\"type\":\"Cat\"},{\"name\":\"Nemo\",\"type\":\"Fish\"}]}]"; var grouped = JSONDeserializer.DeserializePersonAndGroupByGender(json); int i = 0; foreach (var group in grouped) { if (i == 0) { Assert.AreEqual("MALE", group.Key.ToUpper()); } if (i == 1) { Assert.AreEqual("FEMALE", group.Key.ToUpper()); } foreach (var pet in group) { // ToDo Assert check pet names are corret } i++; } }
/// <summary> /// Loads a mapping of trigger name to the JSON file name /// </summary> /// <param name="path">The path to the JSON mapping file</param> /// <returns>A dictionary mapping the trigger name to the JSON file name</returns> Dictionary <string, string> LoadCladToAnimMap(string path) { // Get the text for the file var text = File.ReadAllText(path); // Get it in a convenient form CTFM[] items; if (AssetsType.Cozmo == AssetsType) { // Load Cozmo's particular format var pairs = JSONDeserializer.Deserialize <CozmoCTFM>(text); items = pairs.Pairs; } else { items = JSONDeserializer.Deserialize <CTFM[]>(text); } // Create a more useful mapping var ret = new Dictionary <string, string>(); foreach (var item in items) { ret[item.CladEvent] = item.AnimName; } return(ret); }
/// <summary> /// Looks up the animation group given the trigger name /// </summary> /// <param name="triggerName">The animation trigger name</param> /// <returns>A set of possible animations to display</returns> public IReadOnlyCollection <AnimationGroupItem> AnimationGroupForTrigger(string triggerName) { // See if the description is already loaded if (animationGroupCache.TryGetValue(triggerName, out var ret)) { return(ret); } // look up name for the animation group file if (!animationTriggerName2GroupName.TryGetValue(triggerName, out var partialName)) { return(null); } // Look up the path to the namtion var path = AnimationGroupPath(partialName); // Get the text for the file var text = File.ReadAllText(path); // Get the animation group file in a convenient form var item = JSONDeserializer.Deserialize <AnimationGroup>(text); // cache it if (null != item.Animations) { animationGroupCache[triggerName] = item.Animations; } // return it return(item.Animations); }
public void ReadExternal(IDataInput input) { Json = input.ReadUtf((int)input.ReadUInt32()); var json = JSONParser.ParseObject(Json, 0); var states = JSONDeserializer.Deserialize <ClientSystemStatesNotification>(json); foreach (PropertyInfo prop in typeof(ClientSystemStatesNotification).GetProperties()) { prop.SetValue(this, prop.GetValue(states)); } //foreach (KeyValuePair<string, object> keyPair in json) { // var f = typeof(ClientSystemStatesNotification).GetProperty(keyPair.Key); // if (f == null) continue; // if (keyPair.Value is MFroehlich.Parsing.JSON.JSONArray) { // var tempArrayList = keyPair.Value as MFroehlich.Parsing.JSON.JSONArray; // if (tempArrayList.Count > 0) { // var array = Array.CreateInstance(f.PropertyType.GetElementType(), tempArrayList.Count); // for (int i = 0; i < tempArrayList.Count; i++) array.SetValue(tempArrayList[i], i); // f.SetValue(this, array); // } else // f.SetValue(this, null); // } else { // f.SetValue(this, (dynamic) keyPair.Value); // } //} }
// Token: 0x0600174D RID: 5965 RVA: 0x000869C0 File Offset: 0x00084DC0 public void loadTranslationEconInfo() { string path = ReadWrite.PATH + "/EconInfo_" + Provider.language; if (!ReadWrite.fileExists(path, false, false)) { path = Provider.path + Provider.language + "/EconInfo.json"; if (!ReadWrite.fileExists(path, false, false)) { return; } } IDeserializer deserializer = new JSONDeserializer(); List <UnturnedEconInfo> list = new List <UnturnedEconInfo>(); list = deserializer.deserialize <List <UnturnedEconInfo> >(path); using (List <UnturnedEconInfo> .Enumerator enumerator = list.GetEnumerator()) { while (enumerator.MoveNext()) { UnturnedEconInfo translatedItem = enumerator.Current; UnturnedEconInfo unturnedEconInfo = TempSteamworksEconomy.econInfo.Find((UnturnedEconInfo x) => x.itemdefid == translatedItem.itemdefid); if (unturnedEconInfo != null) { unturnedEconInfo.name = translatedItem.name; unturnedEconInfo.type = translatedItem.type; unturnedEconInfo.description = translatedItem.description; } } } }
private static bool Deserialize(Type t, object value, out object result) { var att = t.GetCustomAttribute <SerializedNameAttribute>(); if (att != null && !typeof(JSONSerializable).IsAssignableFrom(t)) { string _class; if (((JSONObject)value).TryGetValue("_class", out _class)) { t = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t2 => t2.GetCustomAttribute <SerializedNameAttribute>(false)?.SerializedName == _class); } result = Activator.CreateInstance(t); foreach (var member in Member.GetMembers(t)) { var field = member.Value.GetCustomAttribute <SerializedNameAttribute>(); var name = field?.SerializedName ?? member.Name; object v; if (((JSONObject)value).TryGetValue(name, out v)) { member.SetValue(result, JSONDeserializer.Deserialize(member.MemberType, v)); } } return(true); } result = null; return(false); }
/// <summary> /// Loads the information from the moods file /// </summary> /// <param name="configPath">Path to the config folder</param> void LoadMoods(string configPath) { // get the path to the moods file var path = Path.Combine(configPath, "mood_config.json"); // Get the text for the file var text = File.ReadAllText(path); // Get the configuration var d = JSONDeserializer.ToDict(JSONDeserializer.Deserialize <Dictionary <string, object> >(text)); // Set up the allowed value ranges // Poopulate some defaults (these will get overriden) emotionRanges["Happy"] = new MinMax(); emotionRanges["Confident"] = new MinMax(); emotionRanges["Social"] = new MinMax(); emotionRanges["Stimulated"] = new MinMax(); // internalize each of the items // Give ranges to emotion dimensions if (d.TryGetValue("valueRanges", out var valueRanges)) { foreach (var _item in (object[])valueRanges) { // Create a range of acceptable values for this emotion type var mm = new MinMax(); var item = (Dictionary <string, object>)_item; mm.max = (float)(double)item["max"]; mm.min = (float)(double)item["min"]; emotionRanges[(string)item["emotionType"]] = mm; } } // Todo: the decay graphs, etc }
/// <summary> /// Loads the bundle information about the sound banks /// </summary> void SoundbankBundleInfo() { // Create the path to the configuration file var cfgStream = folderWrapper.Stream("SoundbankBundleInfo.json"); if (null == cfgStream) { return; } // Open the sound configuration JSON file' string text; using (var rdr = new StreamReader(cfgStream)) { text = rdr.ReadToEnd(); } // Lets convert the JSON basic object types var cfg = JSONDeserializer.Deserialize <SoundBankInfo[]>(text); // Go thru and convert the configuration into a bank look up table foreach (var entry in cfg) { // Map the soundbank name to the entry soundBank2Info[entry.Name.ToUpper()] = entry; // Cache the bank name IDForString(entry.Name); } // Try reading the initialization file // SoundBank("Init"); }
/// <summary> /// Loads the information from the emotion events files /// </summary> /// <param name="configPath">Path to the config folder</param> void LoadEmotionEvents(string configPath) { // Get the dictionary emotionEvents = new Dictionary <string, EmotionEvent>(); // Enumerate over the directory var files = Directory.EnumerateFiles(configPath, "*.json", SearchOption.AllDirectories); foreach (string currentFile in files) { // Get the text for the file var text = File.ReadAllText(currentFile); // Convert it // Vector style emotion event seems to have just the one type, // but Cozmo has two, so support falling back to it try { var d = JSONDeserializer.Deserialize <Dictionary <string, EmotionEvent[]> >(text); // Add the events to the table foreach (var evt in d["emotionEvents"]) { emotionEvents[evt.name] = evt; } } catch (Exception) { // Single emotion event var evt = JSONDeserializer.Deserialize <EmotionEvent>(text); emotionEvents[evt.name] = evt; } } }
/// <summary> /// Loads the vision subsystem configuredion /// </summary> void LoadVision() { // Get the text for the file var text = File.ReadAllText(Path.Combine(cozmoResourcesPath, "config/engine/vision_config.json")); // Get it in a convenient form visionConfig = JSONDeserializer.ToDict(JSONDeserializer.Deserialize <Dictionary <string, object> >(text)); // Load the vision schedule mediator var vpath = Path.Combine(cozmoResourcesPath, "config/engine/visionScheduleMediator_config.json"); if (File.Exists(vpath)) { text = File.ReadAllText(vpath); var tmp = JSONDeserializer.Deserialize <Dictionary <string, VisionModeSetting[]> >(text); // Rearrange so that we can look up by item var config = (Dictionary <string, VisionModeSetting>)VisionScheduleConfig; foreach (var x in tmp["VisionModeSettings"]) { config[x.mode] = x; } } // Load the information about the classifiers LoadClassifierInfo(); }
public MainWindow() { InitializeComponent(); var content = new JSONDeserializer(); Debug.WriteLine(content.GetReleases("http://www.dnd5eapi.co/api/classes/1")); }
public LeagueClient() { JSONDeserializer.AddDeserializer <object>(Deserialize); JSONSerializer.AddSerializer(Serialize); BackEndServer.Initialize(); Session.Initialize(); BackEndServer.AddService(this.front); }
public virtual void GotGameData(LcdsServiceProxyResponse lcds) { var json = JSONParser.ParseObject(lcds.payload); GroupData = JSONDeserializer.Deserialize <TBDGroupData>(json); if (lobbyStatus != null) { UpdateSlots(); } }
public void ReadExternal(IDataInput input) { Json = input.ReadUtf((int)input.ReadUInt32()); var json = JSONParser.ParseObject(Json); if (json.ContainsKey("broadcastMessages")) { BroadcastMessages = JSONDeserializer.Deserialize <List <BroadcastMessage> >(json["broadcastMessages"]); } }
/// <summary> /// Loads the information from the server_cinfig file /// </summary> /// <param name="configPath">Path to the config folder</param> void LoadServers(string configPath) { // get the path to the server config file var path = Path.Combine(configPath, "server_config.json"); // Get the text for the file var text = File.ReadAllText(path); // Get the dictionary, in a convenient form Servers = JSONDeserializer.Deserialize <Dictionary <string, string> >(text); }
public void ReadExternal(IDataInput input) { Json = input.ReadUtf((int)input.ReadUInt32()); var json = JSONParser.ParseObject(Json); var states = JSONDeserializer.Deserialize <ClientSystemStatesNotification>(json); foreach (PropertyInfo prop in typeof(ClientSystemStatesNotification).GetProperties()) { prop.SetValue(this, prop.GetValue(states)); } }
public JSONClient(Uri baseUrl, IAuthenticator authenticator) : base(baseUrl) { var deserializer = new JSONDeserializer(); this.AddHandler("application/json", deserializer); this.AddHandler("text/json", deserializer); this.AddHandler("text/x-json", deserializer); this.AddHandler("*", deserializer); this.Authenticator = authenticator; }
public override bool Handle(HttpListenerContext context) { Delegate endpoint; if (endpoints.TryGetValue(context.Request.Url.LocalPath, out endpoint)) { JSONObject result; #region Dispatch try { var rawArgs = new JSONArray(); if (context.Request.ContentLength64 > 0) { string str; using (var mem = new MemoryStream((int)context.Request.ContentLength64)) { context.Request.InputStream.CopyTo(mem); str = Encoding.UTF8.GetString(mem.ToArray()); } rawArgs = JSONParser.ParseArray(str); } var types = endpoint.Method.GetParameters(); var changed = new object[rawArgs.Count]; for (var i = 0; i < rawArgs.Count; i++) { changed[i] = JSONDeserializer.Deserialize(types[i].ParameterType, rawArgs[i]); } var raw = endpoint.DynamicInvoke(changed); result = GetResult(raw); } catch (Exception x) { while (x.InnerException != null) { x = x.InnerException; } result = new JSONObject { ["error"] = new JSONObject { ["id"] = 2, ["trace"] = x.StackTrace, ["message"] = x.Message, ["exception"] = x.GetType().Name, } }; } #endregion var bytes = Encoding.UTF8.GetBytes(result.ToJSON()); context.Response.OutputStream.Write(bytes, 0, bytes.Length); return(true); } return(false); }
public async Task <int[]> GetKudosTotals(long summoner) { var json = new JSONObject { ["commandName"] = "TOTALS", ["summonerId"] = summoner }.ToJSON(); var res = await InvokeAsync <LcdsResponseString>("callKudos", json); var parsed = JSONParser.ParseObject(res.Value); return(JSONDeserializer.Deserialize <int[]>(parsed["totals"])); }
private bool OnSimpleDialogMessage(SimpleDialogMessage msg) { switch (msg.TitleCode) { case "championMastery": var arg = JSONParser.ParseObject((string)msg.Params[0]); var rawMastery = JSONDeserializer.Deserialize <EogChampionMasteryDTO>(arg); if (rawMastery.LevelUpList.Any()) { } var stats = new PostGameChampionMastery { Champion = rawMastery.ChampionId, Grade = rawMastery.PlayerGrade, Before = new ChampionMasteryState { Level = rawMastery.ChampionLevelUp ? rawMastery.ChampionLevel - 1 : rawMastery.ChampionLevel, PointsInLevel = rawMastery.ChampionPointsSinceLastLevelBeforeGame + rawMastery.ChampionPointsUntilNextLevelBeforeGame, PointsSinceLevel = rawMastery.ChampionPointsSinceLastLevelBeforeGame, TotalPoints = rawMastery.ChampionPointsBeforeGame }, After = new ChampionMasteryState { Level = rawMastery.ChampionLevel, PointsInLevel = rawMastery.ChampionPointsUntilNextLevelAfterGame + (rawMastery.ChampionPointsGained - rawMastery.ChampionPointsUntilNextLevelBeforeGame) + 1, PointsSinceLevel = rawMastery.ChampionPointsGained - rawMastery.ChampionPointsUntilNextLevelBeforeGame + 1, TotalPoints = rawMastery.ChampionPointsBeforeGame + rawMastery.ChampionPointsGained } }; if (!rawMastery.ChampionLevelUp) { stats.After.PointsInLevel = stats.Before.PointsInLevel; stats.After.PointsSinceLevel = rawMastery.ChampionPointsSinceLastLevelBeforeGame + rawMastery.ChampionPointsGained; } state.ChampionMastery = stats; OnStateChanged(); return(true); case "championMasteryLootGrant": arg = JSONParser.ParseObject((string)msg.Params[0]); var rawLoot = JSONDeserializer.Deserialize <ChampionMasteryLootGrant>(arg); HextechService.Add(state.Hextech, true, rawLoot.LootName, 1, null); OnStateChanged(); break; } return(false); }
private async Task <T> FetchAsync <T>(string url) where T : new() { var req = WebRequest.Create(url); var b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(session.LoginQueue.GasToken.ToJSON())); req.Headers.Add("region", Region.Current.Platform); req.Headers.Add("authorization", "GasTokenRaw " + b64); using (var res = await req.GetResponseAsync()) using (var mem = new MemoryStream()) using (var stream = res.GetResponseStream()) { stream.CopyTo(mem); return(JSONDeserializer.Deserialize <T>(JSONParser.Parse(mem.ToArray()))); } }
private static T ExtractJSON <T>(WADArchive archive, Func <string, string> path) { WADArchive.FileInfo fileInfo; if (archive.TryGetFile(path(Region.Locale.ToLowerInvariant()), out fileInfo)) { return(JSONDeserializer.Deserialize <T>(JSONParser.Parse(archive.Extract(fileInfo)))); } if (archive.TryGetFile(path(GameDataAssets.DefaultLocale), out fileInfo)) { return(JSONDeserializer.Deserialize <T>(JSONParser.Parse(archive.Extract(fileInfo)))); } throw new KeyNotFoundException($"File {path(GameDataAssets.DefaultLocale)} not found"); }
/// <summary> /// Loads the user intents configuration folder /// </summary> void LoadIntents() { // get the path to the animation file var path = Path.Combine(cozmoResourcesPath, "config/engine/behaviorComponent/user_intent_maps.json"); // Skip it if the file doesn't exist if (!File.Exists(path)) { return; } // Get the text for the file var text = File.ReadAllText(path); // Get it in a convenient form var userIntentMap = JSONDeserializer.Deserialize <UserIntentsMap>(text); // Map the cloud intents and the app intents to the user intents var cld = new Dictionary <string, UserIntentMap>(); var app = new Dictionary <string, UserIntentMap>(); foreach (var item in userIntentMap.user_intent_map) { if (null != item.cloud_intent) { cld[item.cloud_intent] = item; } if (null != item.app_intent) { app[item.app_intent] = item; } } Cloud2UserIntent = cld; App2UserIntent = app; // apply the more responses var clr = new Dictionary <string, SimpleVoiceResponse>(); foreach (var item in userIntentMap.simple_voice_responses) { if (null != item.cloud_intent) { clr[item.cloud_intent] = item.response; } } Cloud2Response = clr; }
public void DebugEog() { var file = @"C:\Users\max\desktop\eog.txt"; var lines = File.ReadAllLines(file); new Thread(() => { var stats = JSONDeserializer.Deserialize <EndOfGameStats>(JSONParser.Parse(lines[0])); var a = JSONDeserializer.Deserialize <SimpleDialogMessage>(JSONParser.Parse(lines[1])); var b = JSONDeserializer.Deserialize <SimpleDialogMessage>(JSONParser.Parse(lines[2])); Thread.Sleep(1000); session.HandleMessage(stats); Thread.Sleep(1000); session.HandleMessage(a); Thread.Sleep(1000); session.HandleMessage(b); }).Start(); }
/// <summary> /// Retrieve table metadata using the connection provided. /// </summary> /// <param name="connection"></param> /// <returns></returns> public static TableMetadata TableMetadataRetriever(DSTConnection connection) { TableMetadata tables = new TableMetadata(); var response = connection.RetrieveMetadata(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { tables = JSONDeserializer.DeserializeMetadata(response.Content); } else { Console.WriteLine("HTTP error: " + response.StatusCode + " -> " + response.Content); } return(tables); }
/// <summary> /// Retrieve tables using the connection provided. /// </summary> /// <param name="settings"></param> /// <returns></returns> public static List <Table> TablesRetriever(DSTConnection connection) { List <Table> tables = new List <Table>(); var response = connection.RetrieveTables(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { tables = JSONDeserializer.DeserializeTables(response.Content); } else { Console.WriteLine("HTTP error: " + response.StatusCode + " -> " + response.Content); } return(tables); }
/// <summary> /// Retrieve subjects using the connection provided. /// </summary> /// <param name="settings"></param> /// <returns></returns> public static List <Subject> SubjectsRetriever(DSTConnection connection) { List <Subject> subjects = new List <Subject>(); var response = connection.RetrieveSubjects(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { subjects = JSONDeserializer.DeserializeSubjects(response.Content); } else { Console.WriteLine("HTTP error: " + response.StatusCode + " -> " + response.Content); } return(subjects); }
/// <summary> /// Loads a mapping of trigger name to the JSON file name /// </summary> /// <param name="path">The path to the JSON mapping file</param> /// <returns>A dictionary mapping the trigger name to the JSON file name</returns> static Dictionary <string, string> LoadCladToMapMap(string path) { // Get the text for the file var text = File.ReadAllText(path); // Get it in a convenient form var items = JSONDeserializer.Deserialize <CTMap[]>(text); // Create a more useful mapping var ret = new Dictionary <string, string>(); foreach (var item in items) { ret[item.CladEvent] = item.MapName; } return(ret); }
/// <summary> /// Loads the information from the features file /// </summary> /// <param name="configPath">Path to the config folder</param> void LoadFeatures(string configPath) { // get the path to the features file var path = Path.Combine(configPath, "features.json"); // Get the text for the file var text = File.ReadAllText(path); // Get the dictionary, in a convenient form var items = (object[])JSONDeserializer.JsonToNormal(JSONDeserializer.Deserialize <JsonElement>(text)); // internalize each of the items foreach (var _item in items) { var item = (Dictionary <string, object>)_item; featureToggle[(string)item["feature"]] = (bool)item["enabled"]; } }
// Token: 0x0600172C RID: 5932 RVA: 0x0008596C File Offset: 0x00083D6C public TempSteamworksEconomy(SteamworksAppInfo newAppInfo) { this.appInfo = newAppInfo; TempSteamworksEconomy.econInfo = new List <UnturnedEconInfo>(); IDeserializer deserializer = new JSONDeserializer(); TempSteamworksEconomy.econInfo = deserializer.deserialize <List <UnturnedEconInfo> >(ReadWrite.PATH + "/EconInfo.json"); if (this.appInfo.isDedicated) { this.inventoryResultReady = Callback <SteamInventoryResultReady_t> .CreateGameServer(new Callback <SteamInventoryResultReady_t> .DispatchDelegate(this.onInventoryResultReady)); } else { this.inventoryResultReady = Callback <SteamInventoryResultReady_t> .Create(new Callback <SteamInventoryResultReady_t> .DispatchDelegate(this.onInventoryResultReady)); this.gameOverlayActivated = Callback <GameOverlayActivated_t> .Create(new Callback <GameOverlayActivated_t> .DispatchDelegate(this.onGameOverlayActivated)); } }