/// <summary> /// Creates JSON string from bussines object. /// </summary> /// <param name="Object">Object instance.</param> /// <returns>JSON representation of an object.</returns> public static string JsonItem(TObject Object) { String JsonResponse = "\"Message\":\"\", \"Data\":{1}"; String JsonResponseException = "\"Message\":{0}, \"StackTrace\":{1}, \"Data\":null"; StringBuilder sb = new StringBuilder(); try { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(TObject)); using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(ms)) { json.WriteObject(ms, Object); writer.Flush(); String Json = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); sb.Append("{"); sb.Append(String.Format(JsonResponse, "", Json)); sb.Append("}"); return(sb.ToString()); } } } catch (Exception ex) { sb.Append("{"); sb.Append(String.Format(JsonResponseException, ToJson(ex.Message) + (ex.InnerException != null ? ToJson(ex.InnerException.Message) : ""), ToJson(ex.StackTrace))); sb.Append("}"); return(sb.ToString()); } }
private async Task AppendToTextFileAsync(string fileLocation, T data) { try { using (var stream = new FileStream(fileLocation, FileMode.Create, FileAccess.Write)) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(data.GetType()); serializer.WriteObject(writer, data); writer.Flush(); await Task.CompletedTask; } } } catch (IOException ex) when((ex.HResult & 0xFFFF) == 0x27 || (ex.HResult & 0xFFFF) == 0x70) { Logger.Error("TumblrJsonDownloader:AppendToTextFile: {0}", ex); shellService.ShowError(ex, Resources.DiskFull); crawlerService.StopCommand.Execute(null); } catch { } }
public override void ExecuteResult(ControllerContext context) { Encoding encoding = Encoding.UTF8; if (!String.IsNullOrEmpty(this.ContentType.CharSet)) { try { encoding = Encoding.GetEncoding(this.ContentType.CharSet); } catch (ArgumentException) { throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType)); } } DataContractJsonSerializer dcs = new DataContractJsonSerializer(this.Data.GetType()); this.ContentType.CharSet = encoding.HeaderName; context.HttpContext.Response.ContentType = this.ContentType.ToString(); using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(context.HttpContext.Response.OutputStream, encoding)) { dcs.WriteObject(writer, this.Data); writer.Flush(); } }
static public void Save <T>(string fname, T obj) { try { DataContractJsonSerializerSettings Settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; using (Stream stream = File.Create(fname)) { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(typeof(T), Settings); serializer.WriteObject(writer, obj); writer.Flush(); } } Console.WriteLine("JsonSerializer: Save"); } catch (Exception ex) { Console.WriteLine("Error:" + ex.Message); } }
private void SaveMainTo(string fileName) { var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var serializer = new DataContractJsonSerializer(typeof(MainJSONWrapper), settings); var outfile = new FileStream(fileName, FileMode.Create); var writer = JsonReaderWriterFactory.CreateJsonWriter(outfile, Encoding.UTF8, false, true, " "); var wrap = new MainJSONWrapper(); wrap.archetypes = Archetypes; wrap.scriptables = Scriptables; wrap.textbags = TextBags; serializer.WriteObject(writer, wrap); writer.Flush(); outfile.Flush(); outfile.Close(); outfile.Dispose(); }
public void SerializeNonDC2() { var ser = new DataContractJsonSerializer(typeof(TestData)); StringWriter sw = new StringWriter(); var obj = new TestData() { Foo = "foo", Bar = "bar", Baz = "baz" }; // XML using (var xw = XmlWriter.Create(sw)) ser.WriteObject(xw, obj); var s = sw.ToString(); // since the order is not preserved, we compare only contents. Assert.IsTrue(s.IndexOf("<Foo>foo</Foo>") > 0, "#1-1"); Assert.IsTrue(s.IndexOf("<Bar>bar</Bar>") > 0, "#1-2"); Assert.IsFalse(s.IndexOf("<Baz>baz</Baz>") > 0, "#1-3"); // JSON MemoryStream ms = new MemoryStream(); using (var xw = JsonReaderWriterFactory.CreateJsonWriter(ms)) ser.WriteObject(ms, obj); s = new StreamReader(new MemoryStream(ms.ToArray())).ReadToEnd().Replace('"', '/'); // since the order is not preserved, we compare only contents. Assert.IsTrue(s.IndexOf("/Foo/:/foo/") > 0, "#2-1"); Assert.IsTrue(s.IndexOf("/Bar/:/bar/") > 0, "#2-2"); Assert.IsFalse(s.IndexOf("/Baz/:/baz/") > 0, "#2-3"); }
public static void Jsonify <T>(this T item, Stream stream) { try { // using (var stream = File.Open(path, FileMode.Create)) // { var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(typeof(T), mSettings); serializer.WriteObject(writer, item); writer.Flush(); } } catch (Exception exception) { Debug.WriteLine(exception.ToString()); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } // } } catch (Exception exception) { Debug.WriteLine(exception.ToString()); } }
public void SerializeDeserializeJson() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); var ms = new MemoryStream(); var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.UTF8); MessageSerializer.Serialize(this.MessageDescriptions.GetAccessor(message), writer); writer.Flush(); string actual = Encoding.UTF8.GetString(ms.ToArray()); string expected = @"{""age"":15,""Name"":""Andrew"",""Location"":""http:\/\/localtest\/path"",""Timestamp"":""2008-09-19T08:00:00Z""}"; Assert.AreEqual(expected, actual); ms.Position = 0; var deserialized = new Mocks.TestDirectedMessage(); var reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max); MessageSerializer.Deserialize(this.MessageDescriptions.GetAccessor(deserialized), reader); Assert.AreEqual(message.Age, deserialized.Age); Assert.AreEqual(message.EmptyMember, deserialized.EmptyMember); Assert.AreEqual(message.Location, deserialized.Location); Assert.AreEqual(message.Name, deserialized.Name); Assert.AreEqual(message.Timestamp, deserialized.Timestamp); }
public static string ToJSON(TO obj) { string output = ""; var path = GetTemporayJSONFilePath(); var ser = new DataContractJsonSerializer(typeof(TO), new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }); using (var stream = new FileStream(path, FileMode.Create)) { using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true, " ")) { ser.WriteObject(writer, obj); writer.Flush(); } //stream.Position = 0; } using (var stream = new FileStream(path, FileMode.Open)) { stream.Position = 0; using (var reader = new StreamReader(stream)) { output = reader.ReadToEnd(); } } if (File.Exists(path)) { File.Delete(path); } return(output); }
static string ToJsonImpl <T> ( T obj, bool?indent, IEnumerable <Type> knownTypes) { var serializer = knownTypes == null ? new DataContractJsonSerializer(typeof(T)) : new DataContractJsonSerializer(typeof(T), knownTypes); using (var stream = new MemoryStream()) { if (indent == null) { serializer.WriteObject(stream, obj); } else { var encoding = System.Text.Encoding.UTF8; var writer = JsonReaderWriterFactory .CreateJsonWriter( stream, encoding, true, indent.Value); serializer.WriteObject(writer, obj); writer.Flush(); } _ = stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) return(reader.ReadToEnd()); } }
public void SaveAppConfigSerialize() { var serializer = new DataContractJsonSerializer(typeof(SGAppConfig)); string AppConfig = Environment.CurrentDirectory + "/wwwroot/conf/AppEnvSetting.json"; try { using (var fs = new FileStream(AppConfig, FileMode.Create)) { var encoding = Encoding.UTF8; var ownsStream = false; var indent = true; using (var writer = JsonReaderWriterFactory.CreateJsonWriter(fs, encoding, ownsStream, indent)) { serializer.WriteObject(writer, (_AppConfigInfo as SGAppConfig)); } } } catch (Exception ex) { Log.Error($"\nMessage ---\n{ex.Message}"); Log.Error($"\nHelpLink ---\n{ex.HelpLink}"); Log.Error($"\nStackTrace ---\n{ex.StackTrace}"); } }
public static string ObjectToJsonString <T>(T objectValue, bool format = false) { if (format) { using (var stream = new MemoryStream()) { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(writer, objectValue); writer.Flush(); } return(Encoding.Default.GetString(stream.ToArray())); } } else { var serializer = new DataContractJsonSerializer(typeof(T)); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, objectValue); return(Encoding.Default.GetString(stream.ToArray())); } } }
///<summary> /// Method to convert a custom Object to JSON string /// </summary> /// <param name="pObject">Object that is to be serialized to JSON</param> /// <param name="objectType"></param> /// <returns>JSON string</returns> public static String SerializeObject(Object pobject, Type objectType) { try { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o"); var jsonSerializer = new DataContractJsonSerializer(objectType, settings); //jsonSerializer.DateTimeFormat. string returnValue = ""; using (var memoryStream = new MemoryStream()) { using (var xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream)) { jsonSerializer.WriteObject(xmlWriter, pobject); xmlWriter.Flush(); returnValue = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } } return(returnValue); } catch (Exception e) { throw e; } }
public static async ValueTask UpdateAsync(string wwwrootDir, string? serviceWorkerAssetsManifest) { if (serviceWorkerAssetsManifest == null) return; var serviceWorkerAssetsJsPath = Path.Combine(wwwrootDir, serviceWorkerAssetsManifest); if (!File.Exists(serviceWorkerAssetsJsPath)) return; var serviceWorkerAssetsJs = await File.ReadAllTextAsync(serviceWorkerAssetsJsPath); serviceWorkerAssetsJs = Regex.Replace(serviceWorkerAssetsJs, @"^self\.assetsManifest\s*=\s*", ""); serviceWorkerAssetsJs = Regex.Replace(serviceWorkerAssetsJs, ";\\s*$", ""); var assetsManifestFile = JsonSerializer.Deserialize<AssetsManifestFile>(serviceWorkerAssetsJs); if (assetsManifestFile == null) return; var assetManifestEntry = assetsManifestFile.assets?.First(a => a.url == "index.html"); if (assetManifestEntry == null) return; await using (var indexHtmlStream = File.OpenRead(Path.Combine(wwwrootDir, "index.html"))) { using var sha256 = SHA256.Create(); assetManifestEntry.hash = "sha256-" + Convert.ToBase64String(await sha256.ComputeHashAsync(indexHtmlStream)); } await using (var serviceWorkerAssetsStream = File.OpenWrite(serviceWorkerAssetsJsPath)) { await using var streamWriter = new StreamWriter(serviceWorkerAssetsStream, Encoding.UTF8, 50, leaveOpen: true); streamWriter.Write("self.assetsManifest = "); streamWriter.Flush(); using var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(serviceWorkerAssetsStream, Encoding.UTF8, ownsStream: false, indent: true); new DataContractJsonSerializer(typeof(AssetsManifestFile)).WriteObject(jsonWriter, assetsManifestFile); jsonWriter.Flush(); streamWriter.WriteLine(";"); } }
public static async Task SaveDataAsync(PropertyRoot root, string savePath) { var tempFilePath = savePath + ".tmp"; try { using (var file = File.Open(tempFilePath, FileMode.Create)) { var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( file, Encoding.UTF8, true, true, "\t")) { var serializer = new DataContractJsonSerializer(root.Type, Settings); serializer.WriteObject(writer, root.Structure.Value.Value); await Task.Run(() => writer.Flush()); } } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } } File.Delete(savePath); File.Move(tempFilePath, savePath); } finally { //File.Delete(tempFilePath); } }
public void SaveSettings(string fileName, object settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("String must not be null or empty.", nameof(fileName)); } if (!Path.IsPathRooted(fileName)) { throw new ArgumentException("Invalid path. The path must be rooted.", nameof(fileName)); } string directory = Path.GetDirectoryName(fileName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(settings.GetType(), knownTypes); serializer.WriteObject(writer, settings); writer.Flush(); } } }
/// <summary> /// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>. /// </summary> /// <param name="content">The object to write to the HTTP message.</param> /// <param name="message">The HTTP message to write to.</param> /// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception> protected override void WriteInternal(object content, IHttpOutputMessage message) { #if SILVERLIGHT // Write to the message stream message.Body = delegate(Stream stream) { DataContractJsonSerializer serializer = this.GetSerializer(content.GetType()); serializer.WriteObject(stream, content); }; #else // Get the message encoding Encoding encoding = this.GetContentTypeCharset(message.Headers.ContentType, DEFAULT_CHARSET); DataContractJsonSerializer serializer = this.GetSerializer(content.GetType()); // Write to the message stream message.Body = delegate(Stream stream) { // Using JsonReaderWriterFactory directly to set encoding using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding, false)) { serializer.WriteObject(jsonWriter, content); } }; #endif }
public void Serialize(TraceResult result, Stream stream) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, ownsStream: true, indent: true)) { serializer.WriteObject(writer, result); } }
public static string CreateWriterString(XDocument document) { using (var ms = new MemoryStream()) { if (document.Root is not null) { var t = document.Root.Attribute("type"); if (t is null) { document.Root.Add(new XAttribute("type", "object")); } else { t.Value = "object"; } } var elms = document.Descendants().Where(d => d.Attribute("type") != null && d.Attribute("type").Value == "null").ToList(); foreach (var elm in elms) { elm.ReplaceWith(new XElement(elm.Name, null, elm.FirstAttribute)); } var r = JsonReaderWriterFactory.CreateJsonWriter(ms); document.WriteTo(r); r.Flush(); ms.Position = 0; using (var sr = new StreamReader(ms)) { var f = sr.ReadToEnd(); Console.WriteLine(f); return(f); } } }
public static void SaveToFile(TrainingQueueSubmission payload, string destfilepath) { var container = new TrainingQueueSubmissionRoot { submission = payload }; var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { /* turn it into a json string */ using (var destination = new FileStream(destfilepath, FileMode.CreateNew)) { using (var writer = JsonReaderWriterFactory.CreateJsonWriter(destination, Encoding.UTF8, false)) { var js = new DataContractJsonSerializer(typeof(sherm.core.distributed.model.TrainingQueueSubmissionRoot)); js.WriteObject(writer, container); } } } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } }
public static string ToJSON(object obj) { if (obj == null) { return(null); } try { bool ownsStream = true; bool indent = true; DataContractJsonSerializerSettings jsonSerializerSettings = new DataContractJsonSerializerSettings(); // convert "/Date(1329159196126)/" to "2014-08-06T01:51:31Z" jsonSerializerSettings.DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssZ"); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType(), jsonSerializerSettings); using (MemoryStream memoryStream = new MemoryStream()) { using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8, ownsStream, indent)) { jsonSerializer.WriteObject(jsonWriter, obj); jsonWriter.Flush(); return(Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length)); } } } catch (Exception e) { MyLog.Add(e.ToString()); return(null); } }
/// <summary> /// Write T to json file /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="type">Type</param> /// <param name="path">File name with optional path</param> /// <returns></returns> public static bool ConvertJSonToObjectWithFormatting <T>(T type, string path) { var success = true; try { using var stream = File.Open(path, FileMode.Create); try { using var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true, " "); var serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(writer, type); writer.Flush(); } catch (Exception) { success = false; } } catch (Exception) { success = false; } return(success); }
public void Keep <TValue>(TValue item, string key = null) { try { Type type = item.GetType(); if ((System.Attribute.IsDefined((MemberInfo)type, typeof(DataContractAttribute)) ? 1 : (System.Attribute.IsDefined((MemberInfo)type, typeof(CollectionDataContractAttribute)) ? 1 : 0)) == 0) { return; } using (Stream writeStream = this.Storage.GetWriteStream(this.MakeStorageKey(key, type))) { CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(writeStream, Encoding.UTF8, true, this.Indent, this.IndentChars)) { new DataContractJsonSerializer(type, this.Settings).WriteObject(jsonWriter, (object)item); jsonWriter.Flush(); } } catch (Exception) { } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } } } catch (Exception) { } }
public static void StreamNested(Stream from, Stream to, string [] path) { var reversed = path.Reverse().ToArray(); using (var xr = JsonReaderWriterFactory.CreateJsonReader(from, XmlDictionaryReaderQuotas.Max)) { foreach (var subReader in xr.ReadSubtrees(s => s.Select(n => n.LocalName).SequenceEqual(reversed))) { using (var xw = JsonReaderWriterFactory.CreateJsonWriter(to, Encoding.UTF8, false)) { subReader.MoveToContent(); xw.WriteStartElement("root"); xw.WriteAttributes(subReader, true); subReader.Read(); while (!subReader.EOF) { if (subReader.NodeType == XmlNodeType.Element && subReader.Depth == 1) { xw.WriteNode(subReader, true); } else { subReader.Read(); } } xw.WriteEndElement(); } } } }
private void saveDataToJsonFile(bool original, string filename, XDocument doc) { string path = (original) ? (FolderDispatcher.OriginalPath()) : (FolderDispatcher.TranslationPath()); System.IO.Stream stream; stream = File.Open(path + filename, FileMode.Create); var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true); jsonWriter.WriteStartDocument(); jsonWriter.WriteStartElement("root"); jsonWriter.WriteAttributeString("type", "object"); IEnumerable <XElement> elements = doc.Root.Elements().ToList(); foreach (XElement chapter in elements) { jsonWriter.WriteStartElement(chapter.Name.ToString()); jsonWriter.WriteAttributeString("type", "object"); foreach (XElement element in elements.Descendants()) { jsonWriter.WriteElementString(element.Name.ToString(), element.GetDefaultNamespace().ToString(), element.Value); } } jsonWriter.WriteEndDocument(); jsonWriter.Flush(); stream.Close(); }
public void Convert(TraceResult traceresult, Stream stream) { using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, ownsStream: true, indent: true, indentChars: " ")) { jsonFormatter.WriteObject(jsonWriter, traceresult); } }
private void SaveBlog() { string currentIndex = Path.Combine(Location, Name + "." + BlogType); string newIndex = Path.Combine(Location, Name + "." + BlogType + ".new"); string backupIndex = Path.Combine(Location, Name + "." + BlogType + ".bak"); if (File.Exists(currentIndex)) { using (var stream = new FileStream(newIndex, FileMode.Create, FileAccess.Write)) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(GetType()); serializer.WriteObject(writer, this); writer.Flush(); } } File.Replace(newIndex, currentIndex, backupIndex, true); File.Delete(backupIndex); } else { using (var stream = new FileStream(currentIndex, FileMode.Create, FileAccess.Write)) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(GetType()); serializer.WriteObject(writer, this); writer.Flush(); } } } }
// シリアライズ /// <summary> /// DataContract オブジェクトをシリアル化してファイルに保存する。 /// </summary> public static void 保存する(object 保存するオブジェクト, VariablePath ファイルパス, bool UseSimpleDictionaryFormat = true) { using (var stream = File.Open(ファイルパス.数なしパス, FileMode.Create)) { var culture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true)) { var serializer = new DataContractJsonSerializer(保存するオブジェクト.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = UseSimpleDictionaryFormat }); serializer.WriteObject(writer, 保存するオブジェクト); writer.Flush(); } } finally { Thread.CurrentThread.CurrentCulture = culture; } } }
public static string Serialize <T>(T obj) { CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; string json = null; try { using (MemoryStream stream = new MemoryStream()) { using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true, " ")) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), Settings); serializer.WriteObject(writer, obj); writer.Flush(); } byte[] jsonBytes = stream.ToArray(); json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length); } } catch (Exception exception) { Debug.WriteLine(exception.ToString()); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } return(json); }
/// <summary> /// Save filter rules to the configuration file /// </summary> /// <returns>true on success</returns> public bool Save() { try { string path = GetFilterConfigPath(); using (var stream = File.Open(path, FileMode.Create)) { var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(typeof(FilterConfig), Settings); serializer.WriteObject(writer, conf); writer.Flush(); } } catch (Exception exception) { Debug.WriteLine(exception.ToString()); return(false); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } } } catch (Exception exception) { Debug.WriteLine(exception.ToString()); return(false); } return(true); }