public SystemMapping UnmarshallMappings(string databaseFile, PinballXSystem system) { if (!_file.Exists(databaseFile)) { return(new SystemMapping()); } _logger.Info("Reading mappings from {0}...", databaseFile); try { using (var sr = new StreamReader(databaseFile)) using (JsonReader reader = new JsonTextReader(sr)) { try { var systemMapping = _serializer.Deserialize <SystemMapping>(reader); reader.Close(); return(systemMapping); } catch (Exception e) { _logger.Error(e, "Error parsing vpdb.json, deleting and ignoring."); _crashManager.Report(e, "json"); reader.Close(); File.Delete(databaseFile); return(new SystemMapping()); } } } catch (Exception e) { _logger.Error(e, "Error reading vpdb.json, ignoring."); _crashManager.Report(e, "json"); return(new SystemMapping()); } }
public T Deserialize <T>(string jsonStr) { //StringBuilder sb = new StringBuilder(jsonStr); JsonTextReader jtr = new JsonTextReader(new StringReader(jsonStr)); Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer(); T d = default(T); try { if (converterList.Count > 0) { foreach (var i in converterList) { js.Converters.Add(i); } } d = js.Deserialize <T>(jtr); } catch (Exception er) { jtr.Close(); throw er; } jtr.Close(); jtr = null; return(d); }
public Subscribe GetMsgSubscribe() { if (_type != MessageType.Subscribe) { throw new InvalidOperationException("Message type is not intialized or does not match type: \"Subscribe\""); } Subscribe msg = new Subscribe(); msg.ParseMessage(_reader); _reader.Close(); _reader = null; return(msg); }
private void testSingleJsonResource(string jsonFile) { Support.ErrorList errors = new Support.ErrorList(); Model.Resource singleResult; using (JsonTextReader jr = new JsonTextReader(new System.IO.StreamReader(jsonFile))) { Debug.WriteLine(" Reading from json..."); singleResult = FhirParser.ParseResource(jr, errors); jr.Close(); } if (errors.Count > 0) { Debug.WriteLine("=== Json Parse errors ===" + Environment.NewLine + errors.ToString()); _roundTripFailed = true; } else { string xmlFile = Path.ChangeExtension(jsonFile, ".xml"); using (XmlWriter xw = new XmlTextWriter(new System.IO.StreamWriter(xmlFile))) { Debug.WriteLine(" Writing xml..."); FhirSerializer.SerializeResource(singleResult, xw); } } }
protected virtual void Dispose(bool finalize) { if (_isDisposed) { return; } _isDisposed = true; if (_closeStreamOnDispose) { if (_textReader != null) { _textReader.Dispose(); } if (_JSONReader != null) { _JSONReader.Close(); } } if (!ChoETLFrxBootstrap.IsSandboxEnvironment) { System.Threading.Thread.CurrentThread.CurrentCulture = _prevCultureInfo; } _closeStreamOnDispose = false; if (!finalize) { GC.SuppressFinalize(this); } }
public TPReader(string fileName) { if (true == System.IO.File.Exists(fileName)) { m_strFileName = fileName; } else { throw new Exception(string.Format("The file {0} does not exist", fileName)); } try { StreamReader file = File.OpenText(m_strFileName); JsonTextReader reader = new JsonTextReader(file); JObject joTP = (JObject)JToken.ReadFrom(reader); if (false == ReadFile(m_strFileName)) { m_strFileName = string.Empty; throw new Exception(string.Format("The file could not be parsed as test plan")); } reader.Close(); file.Close(); } catch (Exception ex) { throw new Exception(string.Format("Error in loading test plan: {0}", ex.Message)); } }
/*-------------------------------------------------------------------------- * ReadJsonMovieFile_async *--------------------------------------------------------------------------*/ public static async Task<JArray> ReadJsonMovieFile_async( string JsonMovieFilePath ) { StreamReader sr = null; JsonTextReader jtr = null; JArray movieArray = null; Console.WriteLine( " -- Reading the movies data from a JSON file..." ); operationSucceeded = false; operationFailed = false; try { sr = new StreamReader( JsonMovieFilePath ); jtr = new JsonTextReader( sr ); movieArray = (JArray) await JToken.ReadFromAsync( jtr ); operationSucceeded = true; } catch( Exception ex ) { Console.WriteLine( " ERROR: could not read the file!\n Reason: {0}.", ex.Message ); operationFailed = true; } finally { if( jtr != null ) jtr.Close( ); if( sr != null ) sr.Close( ); } if( operationSucceeded ) { Console.WriteLine( " -- Succeeded in reading the JSON file!" ); return ( movieArray ); } return ( null ); }
public static T Deserializer <T>(Stream stream) { var obj = default(T); StreamReader sReader = null; JsonReader reader = null; try { sReader = new StreamReader(stream); reader = new JsonTextReader(sReader); var serializer = JsonSerializer.Create(DefaultSettings); obj = serializer.Deserialize <T>(reader); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "SimpleWeather: JSONParser: error deserializing"); } finally { reader?.Close(); } return(obj); }
public void ReadDataFromJsonFile() { if (File.Exists(path) == false) { StreamWriter createFile = new StreamWriter(path); createFile.Close(); } StreamReader sr = new StreamReader(path); JsonReader reader = new JsonTextReader(sr); var usersList1 = serializer.Deserialize <List <User> >(reader); reader.Close(); sr.Close(); if (usersList1 == null) { List <User> listToSave = new List <User>(); listToSave.Add(new User(1, "Name", "Surname", "City")); StreamWriter sw = new StreamWriter(path); JsonWriter writer = new JsonTextWriter(sw); serializer.Serialize(writer, listToSave); sw.Close(); writer.Close(); } //read file without problem "file doesnt exist" and "empty file" StreamReader sr1 = new StreamReader(path); JsonReader reader1 = new JsonTextReader(sr1); var usersList2 = serializer.Deserialize <List <User> >(reader1); _userService.Users.AddRange(usersList2); reader1.Close(); sr1.Close(); }
/// <summary> /// 加载JSON /// </summary> /// <param name="type"></param> /// <param name="fileName"></param> /// <returns></returns> private static object LoadJson(Type type, string fileName) { StreamReader file = null; JsonTextReader reader = null; try { file = System.IO.File.OpenText(fileName); reader = new JsonTextReader(file); JsonSerializer serializer = new JsonSerializer(); return(serializer.Deserialize(reader, type)); } catch { return(null); } finally { if (file != null) { file.Close(); } if (reader != null) { reader.Close(); } } }
/// <summary> /// 读取Json文件 /// 必须是.json文件! /// </summary> /// <returns></returns> public static JArray GetJsonFileToJArray(string FilePath) { System.IO.StreamReader file = System.IO.File.OpenText(FilePath); JsonTextReader reader = null; JArray ja = null; try { reader = new JsonTextReader(file); ja = (JArray)JToken.ReadFrom(reader); } catch (Exception _e) { reader.Close(); throw; } finally { if (file != null) { file.Close(); } } return(ja); }
/// <summary> /// Loads the Save file and saves it into SaveData and returns the data too. /// </summary> /// <returns>SaveFile data.</returns> public SaveFile LoadSave() { if (!File.Exists("save.json")) { SaveGame(); } else { using (FileStream fileStream = File.OpenRead("save.json")) using (StreamReader streamReader = new StreamReader(fileStream)) using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { JObject jsonSaveData = JObject.Load(jsonTextReader); jsonTextReader.Close(); streamReader.Close(); fileStream.Close(); SaveFile saveFile = jsonSaveData.ToObject <SaveFile>(); if (CheckSaveFileVersion(SaveFileVersion, saveFile.SaveVersion)) { SaveFile = jsonSaveData.ToObject <SaveFile>(); return(jsonSaveData.ToObject <SaveFile>()); } else { return(null); } } } return(null); }
/// <summary> /// Update keys /// </summary> /// <param name="key"></param> /// <param name="localizedStrings"></param> public void AddOrUpdateKey(string key, IDictionary <string, string> localizedStrings) { foreach (var localized in localizedStrings) { var filePath = Path.Combine(_env.ContentRootPath, _locConfig.Value.Path, localized.Key + ".json"); var cacheKey = $"{_locConfig.Value.SessionStoreKeyName}_{localized.Key}_{key}"; if (!File.Exists(filePath)) { using (Stream str = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) using (var sWriter = new StreamWriter(str)) using (var writer = new JsonTextWriter(sWriter)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName(key); writer.WriteValue(localized.Value); writer.WriteEndObject(); } } else { using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sReader = new StreamReader(stream)) using (var reader = new JsonTextReader(sReader)) { var jobj = JObject.Load(reader); jobj[key] = localized.Value; reader.Close(); File.WriteAllText(filePath, jobj.ToString()); } } } }
public static bool GetAllOptions() { if (File.Exists("./options.json")) { options.Clear(); JsonSerializer serializer = new JsonSerializer(); using (FileStream fs = File.Open("./options.json", FileMode.Open)) using (StreamReader sr = new StreamReader(fs)) using (JsonReader reader = new JsonTextReader(sr)) { while (reader.Read() == true) { if (reader.TokenType == JsonToken.StartObject) { Option _option = serializer.Deserialize <Option>(reader); JObject option = new JObject( new JProperty("option", _option.option), new JProperty("result", _option.result) ); options.Add(option); } } reader.Close(); sr.Close(); sr.Dispose(); fs.Close(); fs.Dispose(); } return(true); } return(false); }
public mySql() { /// <summary> /// 读取JSON文件 /// </summary> /// <param name="key">JSON文件中的key值</param> /// <returns>JSON文件中的value值</returns> string jsonfile = "c://HIS//config.json"; using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile)) { using (JsonTextReader reader = new JsonTextReader(file)) { JObject o = (JObject)JToken.ReadFrom(reader); ip = o["ip"].ToString(); user = o["user"].ToString(); passwd = o["passwd"].ToString(); reader.Close(); file.Close(); //return value; } } }
String getCfg() { if (!File.Exists(cfg)) { return(""); } try { StreamReader file = File.OpenText(cfg); JsonTextReader reader = new JsonTextReader(file); JObject jsonObject = (JObject)JToken.ReadFrom(reader); if (!jsonObject.ContainsKey("world-folder")) { return(""); } String a = (String)jsonObject["world-folder"]; reader.Close(); file.Close(); return(a); } catch (Exception e) { return(""); } }
public bool TryReadFromJsonStream <T>(out T result, JsonSerializerSettings settings = null) { try { using (var s = GetStream()) { StreamReader sw = new StreamReader(s); JsonTextReader reader = new JsonTextReader(sw); if (settings == null) { settings = new JsonSerializerSettings(); } JsonSerializer ser = JsonSerializer.Create(settings); result = ser.Deserialize <T>(reader); reader.Close(); sw.Close(); return(true); } } catch (Exception ex) { result = default(T); return(false); } }
private string FormatJsonString(string str, int spacesub = 4) { //格式化json字符串 var result = str; JsonSerializer serializer = new JsonSerializer(); TextReader tr = new StringReader(str); JsonTextReader jtr = new JsonTextReader(tr); object obj = serializer.Deserialize(jtr); if (obj != null) { StringWriter textWriter = new StringWriter(); JsonTextWriter jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.Indented, Indentation = spacesub, IndentChar = ' ' }; serializer.Serialize(jsonWriter, obj); result = textWriter.ToString(); textWriter.Close(); jsonWriter.Close(); } tr.Close(); jtr.Close(); return(result); }
/// <summary> /// 将Json数据转为对象 /// </summary> /// <typeparam name="T">目标对象</typeparam> /// <param name="jsonText">json数据字符串</param> /// <returns></returns> public static T JsonToObject2 <T>(string jsonText) { Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; StringReader sr = new StringReader(jsonText); Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr); T result = default(T); try { result = (T)json.Deserialize(reader, typeof(T)); } catch { } finally { reader.Close(); } return(result); }
//protected bool ReadUntilMatch() //{ // // split json path // string[] strArray = JsonPath.JsonPathContext.Normalize(_jsonPath).Split(';'); // bool returnObject = false; // if (_depth == null) // { // for (int i = 0; i < strArray.Length; i++) // { // string sign = strArray[i]; // switch (sign) // { // case "$": // { // returnObject = _jsonTextReader.Read(); // _depth = _jsonTextReader.Depth; // break; // } // case "*": // { // while (_jsonTextReader.TokenType != JsonToken.StartObject) // { // returnObject = _jsonTextReader.Read(); // } // _depth = _jsonTextReader.Depth; // break; // } // default: // { // while (returnObject = _jsonTextReader.Read()) // { // if (_jsonTextReader.Value != null && _jsonTextReader.Value.ToString() == strArray[i]) // { // _depth = _jsonTextReader.Depth; // break; // } // else if (i <= strArray.Length - 1) // { // returnObject = false; // } // } // break; // } // } // } // } // else if (strArray[strArray.Length - 1] != "$" && strArray[strArray.Length - 1] != "*") // { // string propertyName = strArray[strArray.Length - 1]; // while (returnObject = _jsonTextReader.Read()) // { // if (_jsonTextReader.Value == propertyName) // break; // } // } // else // { // while (returnObject=_jsonTextReader.Read()) // { // if (_depth == _jsonTextReader.Depth) // break; // } // } // return returnObject; //} public override void Dispose() { if (_jsonTextReader != null) { _jsonTextReader.Close(); } }
public static Task <Object> DeserializerAsync(Stream stream, Type type) { Object obj = null; StreamReader sReader = null; JsonReader reader = null; return(Task.Run(() => { try { sReader = new StreamReader(stream); reader = new JsonTextReader(sReader); var serializer = JsonSerializer.Create(DefaultSettings); obj = serializer.Deserialize(reader, type); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "SimpleWeather: JSONParser: error deserializing"); } finally { reader?.Close(); } return obj; })); }
public static async Task <JArray> ReadJsonMovieFile_async(string jsonMovieFilePath) { StreamReader sr = null; JsonTextReader jtr = null; JArray movieArray = null; Console.WriteLine(" -- Reading the movies data from a JSON file..."); try { sr = new StreamReader(jsonMovieFilePath); jtr = new JsonTextReader(sr); movieArray = (JArray)await JToken.ReadFromAsync(jtr); } catch (Exception ex) { Console.WriteLine(" ERROR: could not read the file!\n Reason: {0}.", ex.Message); } finally { jtr?.Close(); sr?.Close(); } return(movieArray); }
public void LoadDatabase(string path = null) { if (String.IsNullOrWhiteSpace(path)) { path = Program.Options.DataFile; } if (!File.Exists(Program.Options.DataFile)) { using (var writer = File.CreateText(path)) { // Create the file writer.Write("{\n}"); // Write to the stream and flush it writer.Flush(); } } using (var reader = new StreamReader(path, Encoding.UTF8)) { JsonReader jsonReader = new JsonTextReader(reader); // Try to deserialize the stream JsonSerializer serializer = new JsonSerializer(); ImageDataList imgList = serializer.Deserialize <ImageDataList> (jsonReader); ImageDataList.Images.Clear(); if (imgList != null && imgList.imageList != null) { ImageDataList.Images.AddRange(imgList.imageList); } imgList = null; // Null the temporary image list jsonReader.Close(); // Close the jsonReader } SendOnChange(ImageDataChangeType.Loading); }
public static TInfo Deserialize <TInfo>( byte[] payload) where TInfo : Info { var json = ConvertToString(payload); StringReader textReader = null; JsonReader jsonReader = null; try { textReader = new StringReader(json); jsonReader = new JsonTextReader(textReader); return(new JsonSerializer() .Deserialize <TInfo>( jsonReader)); } finally { if (jsonReader != null) { jsonReader.Close(); } else { if (textReader != null) { textReader.Dispose(); } } } }
public static T JsonToObject2 <T>(string jsonText) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown JsonSerializer val = new JsonSerializer(); val.NullValueHandling = NullValueHandling.Ignore; val.ObjectCreationHandling = ObjectCreationHandling.Replace; val.MissingMemberHandling = MissingMemberHandling.Ignore; val.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; StringReader stringReader = new StringReader(jsonText); JsonTextReader val2 = new JsonTextReader((TextReader)stringReader); T result = default(T); try { result = (T)val.Deserialize(val2, typeof(T)); return(result); } catch { } finally { val2.Close(); } return(result); }
public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; if (_closeStreamOnDispose) { if (_textReader != null) { _textReader.Dispose(); } if (_JSONReader != null) { _JSONReader.Close(); } } if (!ChoETLFrxBootstrap.IsSandboxEnvironment) { System.Threading.Thread.CurrentThread.CurrentCulture = _prevCultureInfo; } _closeStreamOnDispose = false; }
private void testJsonFeed(string jsonFile) { Bundle bundleResult; ErrorList errors = new Support.ErrorList(); using (JsonReader jr = new JsonTextReader(new StreamReader(jsonFile))) { Debug.WriteLine(" Reading Json feed..."); bundleResult = FhirParser.ParseBundle(jr, errors); jr.Close(); } if (errors.Count > 0) { Debug.WriteLine("=== Json Feed Parse errors ===" + Environment.NewLine + errors.ToString()); _roundTripFailed = true; } else { string xmlFile = Path.ChangeExtension(jsonFile, ".xml"); using (XmlWriter xw = new XmlTextWriter(new System.IO.StreamWriter(xmlFile))) { Debug.WriteLine(" Writing Xml feed..."); FhirSerializer.SerializeBundle(bundleResult, xw); xw.Flush(); xw.Close(); } } }
/// <summary> /// Load From File /// </summary> /// <param name="file"></param> /// <returns></returns> public static DSSConfig LoadFromFile(string file) { DSSConfig ret = null; StreamReader fstr = null; JsonTextReader reader = null; try { fstr = new StreamReader(file); reader = new JsonTextReader(fstr); JsonSerializer serializer = new JsonSerializer(); ret = serializer.Deserialize <DSSConfig>(reader); } catch (Exception ex) { throw ex; } finally { if (reader != null) { reader.Close(); } if (fstr != null) { fstr.Dispose(); } } return(ret); }
static public int Configure(string githubConfigFile) { GithubConfiguration githubFoncifguration = new GithubConfiguration(); JsonSerializer jsonSerializer = new JsonSerializer(); // Read configuration if exist if (File.Exists(githubConfigFile)) { StreamReader streamReader = new StreamReader(githubConfigFile); Newtonsoft.Json.JsonTextReader jsonTextReader = new JsonTextReader(streamReader); githubFoncifguration = jsonSerializer.Deserialize <GithubConfiguration>(jsonTextReader); jsonTextReader.Close(); streamReader.Close(); } // Show dialog GithubConfigurationForm githubConfigurationForm = new GithubConfigurationForm(githubFoncifguration); if (githubConfigurationForm.ShowDialog() == false) { return(-1); } // Write configuration githubFoncifguration = githubConfigurationForm.ExportGithubConfiguration(); StreamWriter streamWriter = new StreamWriter(githubConfigFile); jsonSerializer.Serialize(streamWriter, githubFoncifguration); streamWriter.Close(); return(0); }
protected static T LoadConfig <T>(string path) where T : class { try { JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace }); // assign default values in case something isn't mentioned in the file T result = (T)Activator.CreateInstance(typeof(T)); using (StreamReader streamReader = new StreamReader(path)) { using (JsonTextReader jsonReader = new JsonTextReader(streamReader)) { result = serializer.Deserialize <T>(jsonReader); jsonReader.Close(); } streamReader.Close(); } return(result); } catch { // something went wrong while loading the file, possibly missing or malformated file // return the default values return((T)Activator.CreateInstance(typeof(T))); } }