public WriteRaw ( string json ) : void | ||
json | string | The raw JSON to write. |
Результат | void |
private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings); using (StreamWriter streamWriter = new StreamWriter(writeStream, this.SupportedEncodings.First())) using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter) { CloseOutput = false }) { jsonTextWriter.WriteRaw(this.Callback + "("); serializer.Serialize(jsonTextWriter, value); jsonTextWriter.WriteRaw(")"); } }
/// <summary> /// Create new JSON data with the original and name value list. /// </summary> /// <param name="json">The original JSON data.</param> /// <param name="nameValues">The name values to add to the JSON data.</param> /// <returns>The new JSON data.</returns> public string Create(string json, JsonNameValue[] nameValues) { // Using string builder. StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); // Create the writer. using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { writer.WriteStartObject(); writer.WriteRaw(json.Trim(new char[] { '{', '}' }) + ","); // For each name value pair. foreach (JsonNameValue item in nameValues) { writer.WritePropertyName(item.Name); writer.WriteValue(item.Value); } // Write the end object. writer.WriteEndObject(); } // Return the JSON data. return(sb.ToString()); }
private void Calibration_FrameArrived(object sender, BodyFrameArrivedEventArgs e) { kc.Controller_FrameArrived(sender, e); if (kc.Arm != ArmPointing.Nothing) { float pointedX = kc.GetPointedX(); float pointedY = kc.GetPointedY(); DataLog.Log(DataLog.DebugLevel.Message, "Calibrated with X=" + pointedX.ToString() + " Y=" + pointedY.ToString()); if (!File.Exists(OPT_FILE)) File.Create(OPT_FILE).Close(); List<float> l = new List<float>(); l.Add(pointedX); l.Add(pointedY); StreamWriter cal_file = File.CreateText(OPT_FILE); JsonTextWriter cal_writer = new JsonTextWriter(cal_file); string data = JsonConvert.SerializeObject(l); cal_writer.WriteRaw(data); cal_file.Close(); this.Close(); } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { var json = JsonConvert.SerializeObject(_value); using (var jw = new JsonTextWriter(new StreamWriter(stream))) { jw.WriteRaw(json); jw.Flush(); } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { var json = JsonConvert.SerializeObject(_value, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); using (var jw = new JsonTextWriter(new StreamWriter(stream))) { jw.WriteRaw(json); jw.Flush(); } }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { var jw = new JsonTextWriter(new StreamWriter(stream)) { Formatting = Formatting.Indented }; jw.WriteRaw(JsonConvert.SerializeObject(_value)); jw.Flush(); return Task.FromResult<object>(null); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var p = value as GeoPrecision; if (p == null) { writer.WriteNull(); return; } using (var sw = new StringWriter()) using (var localWriter = new JsonTextWriter(sw)) { serializer.Serialize(localWriter, p.Precision); localWriter.WriteRaw(p.Unit.GetStringValue()); var s = sw.ToString(); writer.WriteValue(s); } }
/// <summary> /// Metoda scrie un rezultatul serializarii in json a obiectului _responseValue /// </summary> protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { var jw = new JsonTextWriter(new StreamWriter(stream)) { Formatting = Formatting.Indented }; var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = _contractResolver }; var jsonResult = JsonConvert.SerializeObject(_responseValue, jsonSettings); jw.WriteRaw(jsonResult); jw.Flush(); return Task.FromResult<object>(null); }
/// <summary> /// 使用第三方类库Newtonsoft将对象转换成JSON字符串。 /// </summary> /// <param name="objectT">要转换的对象。</param> /// <returns></returns> public static String ToJson(object objectT) { IsoDateTimeConverter timeConverter = new IsoDateTimeConverter(); //这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式 timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"; StringBuilder sbJSON; string rawJSON = JsonConvert.SerializeObject(objectT, Newtonsoft.Json.Formatting.Indented, timeConverter); StringWriter sw = new StringWriter(); JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); writer.WriteRaw(rawJSON); writer.Flush(); sbJSON = sw.GetStringBuilder(); return(sbJSON.ToString()); }
/// <summary> /// 泛型对象转换到JSON表示字符串 /// </summary> /// <param name="objectT">目标对象</param> /// <param name="totalResults">总记录数</param> /// <returns>返回JSON表示字符串</returns> public static string ToJSON(object objectT, int totalResults) { StringBuilder sbJSON; string rawJSON = JsonConvert.SerializeObject(objectT); StringWriter sw = new StringWriter(); JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); writer.WriteStartObject(); writer.WritePropertyName("TotalRecord"); //总记录数 writer.WriteValue(totalResults); writer.WritePropertyName("Data"); //数据集合 writer.WriteRaw(rawJSON); writer.WriteEndObject(); writer.Flush(); sbJSON = sw.GetStringBuilder(); return(sbJSON.ToString()); }
public override void ExecuteResult(ControllerContext context) { JsonTextWriter jwriter = new JsonTextWriter(context.HttpContext.Response.Output); context.HttpContext.Response.ContentType = "application/rss+json"; if (!ObjectCacheManager<string>.Instance.Contains("DefaultFeed")) { StringWriter sw = new StringWriter(); XmlDocument doc = new XmlDocument(); Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed); using (XmlWriter writer = XmlWriter.Create(sw)) { rssFormatter.WriteTo(writer); } doc.LoadXml(sw.ToString()); ObjectCacheManager<string>.Instance.Add("DefaultFeed", JsonConvert.SerializeXmlNode(doc)); } jwriter.WriteRaw(ObjectCacheManager<string>.Instance["DefaultFeed"]); }
public static void TestResponse(string url, string fileName, string body = null, string method = Methods.Get, Codes expectedCode = Codes.Succeeded, string acceptHeader = null) { if (body != null && (method == Methods.Get || method == Methods.Delete)) { //Add the arguments as a url-encoded query string string args = HttpUtility.UrlEncode(body); url += "?" + args; } var httpRequest = (HttpWebRequest) WebRequest.Create(url); httpRequest.KeepAlive = false; httpRequest.Method = method; httpRequest.ContentType = @"application/json"; if (acceptHeader != null) { httpRequest.Accept = acceptHeader; } if (body != null && method != Methods.Get) { httpRequest.ContentLength = body.Length; using (var sw = new StreamWriter(httpRequest.GetRequestStream())) { using (var jr = new JsonTextWriter(sw)) { jr.WriteRaw(body); } } } else { httpRequest.ContentLength = 0; } if (expectedCode == Codes.Succeeded || expectedCode == Codes.SucceededNewRepresentation) { ErrorNotExpected(httpRequest, fileName); } else if (expectedCode == Codes.SucceededValidation) { ErrorNotExpectedNoContent(httpRequest); } else { ErrorExpected(httpRequest, (int) expectedCode); } }
protected static void InitializeConfiguration() { new Configuration(); Console.WriteLine("Configuration loaded!"); Thread.Sleep(1000); var usingmysql = Configuration.IsMySQLEnabled ? "YES" : "NO"; Console.WriteLine("Using MySQL: " + usingmysql); if (Configuration.IsMySQLEnabled) { Console.WriteLine("Connecting to MySQL"); new WebService(); while (!WebService.ConnectionEntablished) Thread.Sleep(100); Console.WriteLine("Connected!"); } else if (!File.Exists("Settings.ini")) { Console.WriteLine("Configuration file not found. Enter required information." + Environment.NewLine); Console.Write("League of Legends game path: "); var GamePath = Console.ReadLine(); Console.Write(Environment.NewLine + "Select region [EUW, EUNE, NA, TR, ...]: "); var Region = Console.ReadLine(); Console.Write(Environment.NewLine + "Max bots value: "); var MaxBots = Console.ReadLine(); Console.Write(Environment.NewLine + "Queue type: [ARAM, MEDIUM_BOT, EASY_BOT, NORMAL5X5]: "); var Queue = Console.ReadLine(); string SelectedDifficulty = string.Empty; int SelectedQueue = int.MaxValue; switch (Queue) { case "MEDIUM_BOT": SelectedDifficulty = "MEDIUM"; SelectedQueue = 33; break; case "EASY_BOT": SelectedQueue = 32; SelectedDifficulty = "EASY"; break; case "ARAM": SelectedQueue = 65; break; case "NORMAL5X5": SelectedQueue = 2; break; } if (MaxBots == null || GamePath == null || SelectedQueue == int.MaxValue || Region == null) { Console.WriteLine("Some of settings was left not set. Please run ChallengerBot again and set all settings as it should be."); return; } var mbots = String.Join("", MaxBots.Where(char.IsDigit)); Settings SFile = new Settings { GamePath = GamePath, MaxBots = Convert.ToInt32(mbots), Difficulty = SelectedDifficulty, QueueType = SelectedQueue, Region = Region.ToUpper() }; WebService.Setting = SFile; using (StreamWriter file = File.CreateText("Settings.ini")) using (JsonTextWriter writer = new JsonTextWriter(file)) { writer.WriteRaw(JsonConvert.SerializeObject(SFile, Formatting.Indented)); } Thread.Sleep(1000); Console.WriteLine("Settings.ini file saved."); } else if (File.Exists("Settings.ini")) Configuration.LoadSettings(); if (!File.Exists("accounts.txt") && !Configuration.IsMySQLEnabled) { Console.WriteLine("Missing accounts.txt file."); Console.WriteLine("One account per line. " + Environment.NewLine + " Format: accountname|accountpassword|maxlevel[1-31]|xpboostbuy[0 - NO and 1 YES]"); while (true) Thread.Sleep(100); } else { int LoadedPlayers = 0; StreamReader file = new StreamReader("accounts.txt"); string line; while ((line = file.ReadLine()) != null) { string[] account = line.Split('|'); bool boost = account[3] != "0"; Accounts bot = new Accounts { Account = account[0], Password = account[1], Maxlevel = Convert.ToInt32(account[2]), Autoboost = boost }; WebService.Players.Add(bot); LoadedPlayers++; } Console.WriteLine("Loaded " + LoadedPlayers + " players."); file.Close(); } if (!File.Exists("version.txt")) ClientVersion = Controller.GetCurrentVersion(WebService.Setting.GamePath); else ClientVersion = File.ReadAllText("version.txt"); Console.WriteLine("Client version: " + ClientVersion); Console.WriteLine("Selected region: " + WebService.Setting.Region); Console.WriteLine("Bot will start in few seconds..."); System.Timers.Timer eTimer = new System.Timers.Timer { AutoReset = false, Interval = 3000 }; eTimer.Elapsed += InitializeBotting; eTimer.Start(); }
public static void WriteEnvironmentSettings(IEnumerable<LoadedEnvironments> environments) { string environmnentJsonFile = Path.Combine(Directory.GetCurrentDirectory(), ENVIRONMENT_FILE_NAME); try { using (StreamWriter file = File.CreateText(environmnentJsonFile)) using (JsonTextWriter writer = new JsonTextWriter(file)) { foreach (var environment in environments) { var jsonEnvironment = JsonConvert.SerializeObject(environment); writer.WriteRaw(jsonEnvironment); } } } catch (Exception ex) { MessageBox.Show($"{Constants.EnvironmentMessages.ErrorWritingFile}{ex}", Constants.EnvironmentMessages.ErrorWritingFileCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } var response = context.HttpContext.Response; response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (Data != null) { if (!AlreadyJson) { var writer = new JsonTextWriter(response.Output); var settings = new JsonSerializerSettings(); settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.NullValueHandling = NullValueHandling.Ignore; var serializer = JsonSerializer.Create(settings); serializer.Serialize(writer, Data); writer.Flush(); } else { var writer = new JsonTextWriter(response.Output); writer.WriteRaw(Data.ToString()); writer.Flush(); } } }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { bool isJsonp = JsonpCallbackFunction != null; // Create a serializer JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); // Create task writing the serialized content return Task.Factory.StartNew(() => { using ( var jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, Encoding)) { CloseOutput = false }) { if (isJsonp) { jsonTextWriter.WriteRaw(JsonpCallbackFunction + "("); jsonTextWriter.Flush(); } serializer.Serialize(jsonTextWriter, value); jsonTextWriter.Flush(); if (isJsonp) { jsonTextWriter.WriteRaw(")"); jsonTextWriter.Flush(); } } }); }
void TrStmtList(List<Statement/*!*/>/*!*/ stmts) { Contract.Requires(cce.NonNullElements(stmts)); List<LocalVariable> AllDecls = new List<LocalVariable>(); using (WriteArray()) { j.WriteValue(KremlinAst.ESequence); using (WriteArray()) { WriteEUnit(); // in case the statement list is empty foreach (Statement ss in stmts) { // JsonTextWriter is forward-only, but after calling TrStmt() we may need // to go back and inject new ELet statements to introduce temp variables. // So call TrStmt() once to generate code to a throw-away MemoryStream, // but remember what temps need to be introduced. Then introduce them // and call TrStmt() once more, to generate the actual Json. JsonTextWriter oldj = j; VariableTracker oldtracker = VarTracker.Clone(); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter newj = new JsonTextWriter(sw); newj.Formatting = oldj.Formatting; newj.Indentation = oldj.Indentation; j = newj; var oldVarDeclsList = varDeclsList; varDeclsList = new List<LocalVariable>(); TrStmt(ss); j = oldj; VarTracker = oldtracker; var decls = varDeclsList; // Grab the set of just-declared variables generated by the first TrStmt() pass varDeclsList = null; // Switch modes for next TrStmt() pass AllDecls.AddRange(decls); // Accumulate the set of all variables this stmt list has generated foreach (var l in decls) { // ELet v in { Stmt j.WriteStartArray(); j.WriteValue(KremlinAst.ELet); j.WriteStartArray(); WriteBinder(l, l.Name, true); // lident WriteDefaultValue(l.Type); // = default VarTracker.Push(l); // "in" is the contents that follow j.WriteStartArray(); j.WriteValue(KremlinAst.ESequence); j.WriteStartArray(); WriteEUnit(); } newj.Close(); string RawJson = sb.ToString(); if (RawJson != "") { j.WriteRaw(","); j.WriteWhitespace("\n"); j.WriteRaw(RawJson); // Now paste the JSON } if (ss.Labels != null) { // bugbug: these appear to be used to support "Break" statements. j.WriteComment("Labels are unsupported: " + ss.Labels.Data.AssignUniqueId("after_", idGenerator)); } varDeclsList = oldVarDeclsList; } // Now that all statements in the list have been generated, close out the nested ELets generated above AllDecls.Reverse(); foreach (var l in AllDecls) { VarTracker.Pop(l); j.WriteEndArray(); // Closing out the expr list in the ESequence j.WriteEndArray(); // Closing out the array aboce ESequence j.WriteEndArray(); // Closing out the list of binder * expr * expr j.WriteEndArray(); // Closing out the array above ELet } } } }
private void WriteFile() { StreamWriter movie_file = File.CreateText(MOVIE_FILE); StreamWriter book_file = File.CreateText(BOOK_FILE); StreamWriter music_file = File.CreateText(MUSIC_FILE); StreamWriter track_file = File.CreateText(TRACK_FILE); JsonTextWriter movie_writer = new JsonTextWriter(movie_file); JsonTextWriter book_writer = new JsonTextWriter(book_file); JsonTextWriter music_writer = new JsonTextWriter(music_file); JsonTextWriter track_writer = new JsonTextWriter(track_file); string data = JsonConvert.SerializeObject(movies); movie_writer.WriteRaw(data); movie_file.Close(); data = JsonConvert.SerializeObject(books); book_writer.WriteRaw(data); book_file.Close(); data = JsonConvert.SerializeObject(musics); music_writer.WriteRaw(data); music_file.Close(); data = JsonConvert.SerializeObject(tracklists); track_writer.WriteRaw(data); track_file.Close(); }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var stream = File.Open(PathUtil.Combine(Caminho, "\\logcrash.json"), FileMode.OpenOrCreate); var textWriter = new JsonTextWriter(new StreamWriter(stream)); textWriter.WriteRaw(JsonConvert.SerializeObject(e, Formatting.Indented)); textWriter.Flush(); stream.Flush(); stream.Dispose(); }
public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); }
public void ParmsObjectAction() { var url1 = "http://*****:*****@"application/json"; var parm1 = new JObject(new JProperty("value", 101)); var parm2 = new JObject(new JProperty("value", MostSimple1AsRef())); var parms = new JObject(new JProperty("parm1", parm1), new JProperty("parm2", parm2)); var body = parms.ToString(); httpRequest.ContentLength = body.Length; using (var sw = new StreamWriter(httpRequest.GetRequestStream())) { using (var jr = new JsonTextWriter(sw)) { jr.WriteRaw(body); } } using (var response = (HttpWebResponse)httpRequest.GetResponse()) { // Code here var rc = response.StatusCode; } //Console.WriteLine("Complete iteration#" + i); Thread.Sleep(100); } catch (Exception e) { //Console.WriteLine("Failed iteration#" + i + " " + e.Message); } } }
public static void WriteRegistryKeySettings(MonitoredRegistryKey monitoredRegistryKey, bool firstLoad = false) { string environmnentJsonFile = Path.Combine(Directory.GetCurrentDirectory(), REGISTRYKEY_FILE_NAME); try { using (StreamWriter file = File.CreateText(environmnentJsonFile)) using (JsonTextWriter writer = new JsonTextWriter(file)) { var jsonRegistryKey = JsonConvert.SerializeObject(firstLoad ? GetInitialRegistryKey() : monitoredRegistryKey); writer.WriteRaw(jsonRegistryKey); } } catch (Exception ex) { MessageBox.Show($"{Constants.RegistryKeyMessages.ErrorWritingFile}{ex}", Constants.RegistryKeyMessages.ErrorWritingFileCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
public static void WriteGeneralSettings(General general) { string generalJsonFile = Path.Combine(Directory.GetCurrentDirectory(), GENERAL_FILE_NAME); try { using (StreamWriter file = File.CreateText(generalJsonFile)) using (JsonTextWriter writer = new JsonTextWriter(file)) { var jsonGeneralSettings = JsonConvert.SerializeObject(general); writer.WriteRaw(jsonGeneralSettings); } } catch (Exception ex) { MessageBox.Show($"{Constants.GeneralMessages.ErrorWritingFile}{ex}", Constants.GeneralMessages.ErrorWritingFileCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
/// <summary> /// Write the formatted event output. /// </summary> /// <param name="eventEntry">The event data to be formatted.</param> /// <param name="writer">The writer to receive the formatted output.</param> public void WriteEvent(EventEntry eventEntry, TextWriter writer) { Guard.ArgumentNotNull(eventEntry, "eventEntry"); using (var jsonWriter = new JsonTextWriter(writer) { CloseOutput = false, Formatting = this.formatting }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(PropertyNames.ProviderId); jsonWriter.WriteValue(eventEntry.ProviderId); jsonWriter.WritePropertyName(PropertyNames.EventId); jsonWriter.WriteValue(eventEntry.EventId); jsonWriter.WritePropertyName(PropertyNames.Keywords); jsonWriter.WriteValue((long)eventEntry.Schema.Keywords); jsonWriter.WritePropertyName(PropertyNames.Level); jsonWriter.WriteValue((int)eventEntry.Schema.Level); jsonWriter.WritePropertyName(PropertyNames.Message); jsonWriter.WriteValue(eventEntry.FormattedMessage); jsonWriter.WritePropertyName(PropertyNames.Opcode); jsonWriter.WriteValue((int)eventEntry.Schema.Opcode); jsonWriter.WritePropertyName(PropertyNames.Task); jsonWriter.WriteValue((int)eventEntry.Schema.Task); jsonWriter.WritePropertyName(PropertyNames.Version); jsonWriter.WriteValue(eventEntry.Schema.Version); jsonWriter.WritePropertyName(PropertyNames.Payload); EventEntryUtil.JsonWritePayload(jsonWriter, eventEntry); jsonWriter.WritePropertyName(PropertyNames.EventName); jsonWriter.WriteValue(eventEntry.Schema.EventName); jsonWriter.WritePropertyName(PropertyNames.Timestamp); jsonWriter.WriteValue(eventEntry.GetFormattedTimestamp(this.DateTimeFormat)); jsonWriter.WriteEndObject(); // Write an entry separator so all the logs can be read as an array, // adding the [] chars to the raw written data ( i.e: "[" + raw + "]" ) // where raw = {log1},{log2}, ... {logN}, jsonWriter.WriteRaw(EntrySeparator); // Writes new line when indented if (jsonWriter.Formatting == Newtonsoft.Json.Formatting.Indented) { jsonWriter.WriteRaw("\r\n"); } } }
public void Save() { try { using (StreamWriter file = File.CreateText(_filePath)) using (JsonTextWriter writer = new JsonTextWriter(file)) { string json = JsonConvert.SerializeObject(this); writer.WriteRaw(json); } } catch (Exception ex) { throw new ApplicationException("Could not write to settings file. " + ex); } }
public static void WriteToolsSettings(IEnumerable<LoadedTools> tools) { string toolJsonFile = Path.Combine(Directory.GetCurrentDirectory(), TOOLS_FILE_NAME); try { using (StreamWriter file = File.CreateText(toolJsonFile)) using (JsonTextWriter writer = new JsonTextWriter(file)) { foreach (var tool in tools) { var jsonTool = JsonConvert.SerializeObject(tool); writer.WriteRaw(jsonTool); } } } catch (Exception ex) { MessageBox.Show($"{Constants.ToolMessages.ErrorWritingFile}{ex}", Constants.ToolMessages.ErrorWritingFileCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); Assert.AreEqual(expected, result); }
public bool SaveToFile(string filename) { try { using (StreamWriter sr = new StreamWriter(filename)) { using (JsonTextWriter jr = new JsonTextWriter(sr)) { jr.WriteRaw("["); jr.WriteStartObject(); jr.WritePropertyName("FlightType"); jr.WriteValue("V1"); jr.WritePropertyName("Date"); jr.WriteValue(DateTime.Now.ToString()); jr.WriteEndObject(); jr.WriteRaw(","); jr.WriteWhitespace(Environment.NewLine); for (int i = 0; i < entries.Count; i++) { jr.WriteStartObject(); jr.WritePropertyName("T"); jr.WriteValue(entries[i].offsettime); if (entries[i].IsPosSet) { jr.WritePropertyName("Pos"); jr.WriteStartArray(); jr.WriteValue(entries[i].pos.X); jr.WriteValue(entries[i].pos.Y); jr.WriteValue(entries[i].pos.Z); jr.WriteEndArray(); if (entries[i].timetofly != 0) { jr.WritePropertyName("FlyTime"); jr.WriteValue(entries[i].timetofly); } } if (entries[i].IsDirSet) { jr.WritePropertyName("Dir"); jr.WriteStartArray(); jr.WriteValue(entries[i].dir.X); jr.WriteValue(entries[i].dir.Y); jr.WriteValue(entries[i].dir.Z); jr.WriteEndArray(); if (entries[i].timetopan != 0) { jr.WritePropertyName("PanTime"); jr.WriteValue(entries[i].timetopan); } } if (entries[i].IsZoomSet) { jr.WritePropertyName("Z"); jr.WriteValue(entries[i].zoom); if (entries[i].timetozoom != 0) { jr.WritePropertyName("ZTime"); jr.WriteValue(entries[i].timetozoom); } } if ( entries[i].IsMessageSet ) { jr.WritePropertyName("Msg"); jr.WriteValue(entries[i].message); if (entries[i].messagetime != 0) { jr.WritePropertyName("MsgTime"); jr.WriteValue(entries[i].messagetime); } } jr.WriteEndObject(); if ( i < entries.Count-1 ) jr.WriteRaw(","); jr.WriteWhitespace(Environment.NewLine); } jr.WriteRaw("]"); } } return true; } catch { } return false; }
public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); }
private static void DumpOpCodes() { using (var output = new StreamWriter(@"C:\tsv\pets\vmjs\src\runtime\opcodes.js")) using (var writer = new JsonTextWriter(output) { Formatting = Formatting.Indented }) { var fields = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField); var opCodes = (from fi in fields select new {fi.Name, OpCode = (OpCode) fi.GetValue(null)}) .OrderBy(x => (uint) x.OpCode.Value) .ToArray(); Action<string, object> prop = (name, value) => { writer.WritePropertyName(name); writer.WriteValue(value); }; Action<string, string> propEnum = (name, value) => { writer.WritePropertyName(name); writer.WriteRawValue(value); }; Action<OpCode> dump = opCode => { writer.WriteStartObject(); prop("name", opCode.Name); prop("size", opCode.Size); prop("value", opCode.Value); propEnum("operand", "OperandType." + opCode.OperandType); propEnum("flow", "FlowControl." + opCode.FlowControl); propEnum("type", "OpCodeType." + opCode.OpCodeType); propEnum("pop", "StackBehaviour." + opCode.StackBehaviourPop); propEnum("push", "StackBehaviour." + opCode.StackBehaviourPush); writer.WriteEndObject(); }; var shortOpCodes = opCodes.Where(x => x.OpCode.Size == 1).ToDictionary(x => (int) x.OpCode.Value, x => x.Name); var longOpCodes = opCodes.Where(x => x.OpCode.Size > 1).ToDictionary(x => x.OpCode.Value & 0xff, x => x.Name); writer.WriteRaw("// warning: this file was auto generated!\n"); writer.WriteRaw("var OpCodes = "); writer.WriteStartObject(); foreach (var f in opCodes) { writer.WritePropertyName(f.Name); dump(f.OpCode); } writer.WriteEndObject(); writer.WriteRaw(";\n"); writer.WriteRaw("var ShortOpCodes = "); writer.WriteStartArray(); for (var i = 0; i <= 255; i++) { string name; if (shortOpCodes.TryGetValue(i, out name)) { writer.WriteRawValue("OpCodes." + name); } else { writer.WriteNull(); } } writer.WriteEndArray(); writer.WriteRaw(";\n"); var maxLongOpCode = longOpCodes.Keys.Max(); writer.WriteRawValue("var LongOpCodes = "); writer.WriteStartArray(); for (var i = 0; i <= maxLongOpCode; i++) { string name; if (longOpCodes.TryGetValue(i, out name)) { writer.WriteRawValue("OpCodes." + name); } else { writer.WriteNull(); } } writer.WriteEndArray(); writer.WriteRaw(";\n"); } }