2
// Copyright (c) 2007 James Newton-King
4
// Permission is hereby granted, free of charge, to any person
5
// obtaining a copy of this software and associated documentation
6
// files (the "Software"), to deal in the Software without
7
// restriction, including without limitation the rights to use,
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
// copies of the Software, and to permit persons to whom the
10
// Software is furnished to do so, subject to the following
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
// OTHER DEALINGS IN THE SOFTWARE.
27
using System.Collections.Generic;
28
using System.Globalization;
29
using System.Runtime.Serialization;
33
using NUnit.Framework;
35
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
36
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
37
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
39
using Newtonsoft.Json;
41
using Newtonsoft.Json.Converters;
42
using Newtonsoft.Json.Utilities;
44
namespace Newtonsoft.Json.Tests
47
public class JsonTextWriterTest : TestFixtureBase
50
public void CloseOutput()
52
MemoryStream ms = new MemoryStream();
53
JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms));
55
Assert.IsTrue(ms.CanRead);
57
Assert.IsFalse(ms.CanRead);
59
ms = new MemoryStream();
60
writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false };
62
Assert.IsTrue(ms.CanRead);
64
Assert.IsTrue(ms.CanRead);
68
public void ValueFormatting()
70
StringBuilder sb = new StringBuilder();
71
StringWriter sw = new StringWriter(sb);
73
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
75
jsonWriter.WriteStartArray();
76
jsonWriter.WriteValue('@');
77
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
78
jsonWriter.WriteValue(true);
79
jsonWriter.WriteValue(10);
80
jsonWriter.WriteValue(10.99);
81
jsonWriter.WriteValue(0.99);
82
jsonWriter.WriteValue(0.000000000000000001d);
83
jsonWriter.WriteValue(0.000000000000000001m);
84
jsonWriter.WriteValue((string)null);
85
jsonWriter.WriteValue((object)null);
86
jsonWriter.WriteValue("This is a string.");
87
jsonWriter.WriteNull();
88
jsonWriter.WriteUndefined();
89
jsonWriter.WriteEndArray();
92
string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
93
string result = sb.ToString();
95
Console.WriteLine("ValueFormatting");
96
Console.WriteLine(result);
98
Assert.AreEqual(expected, result);
102
public void NullableValueFormatting()
104
StringWriter sw = new StringWriter();
105
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
107
jsonWriter.WriteStartArray();
108
jsonWriter.WriteValue((char?)null);
109
jsonWriter.WriteValue((char?)'c');
110
jsonWriter.WriteValue((bool?)null);
111
jsonWriter.WriteValue((bool?)true);
112
jsonWriter.WriteValue((byte?)null);
113
jsonWriter.WriteValue((byte?)1);
114
jsonWriter.WriteValue((sbyte?)null);
115
jsonWriter.WriteValue((sbyte?)1);
116
jsonWriter.WriteValue((short?)null);
117
jsonWriter.WriteValue((short?)1);
118
jsonWriter.WriteValue((ushort?)null);
119
jsonWriter.WriteValue((ushort?)1);
120
jsonWriter.WriteValue((int?)null);
121
jsonWriter.WriteValue((int?)1);
122
jsonWriter.WriteValue((uint?)null);
123
jsonWriter.WriteValue((uint?)1);
124
jsonWriter.WriteValue((long?)null);
125
jsonWriter.WriteValue((long?)1);
126
jsonWriter.WriteValue((ulong?)null);
127
jsonWriter.WriteValue((ulong?)1);
128
jsonWriter.WriteValue((double?)null);
129
jsonWriter.WriteValue((double?)1.1);
130
jsonWriter.WriteValue((float?)null);
131
jsonWriter.WriteValue((float?)1.1);
132
jsonWriter.WriteValue((decimal?)null);
133
jsonWriter.WriteValue((decimal?)1.1m);
134
jsonWriter.WriteValue((DateTime?)null);
135
jsonWriter.WriteValue((DateTime?)new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc));
136
#if !PocketPC && !NET20
137
jsonWriter.WriteValue((DateTimeOffset?)null);
138
jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero));
140
jsonWriter.WriteEndArray();
143
string json = sw.ToString();
146
#if !PocketPC && !NET20
147
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]";
149
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]";
152
Assert.AreEqual(expected, json);
156
public void WriteValueObjectWithNullable()
158
StringWriter sw = new StringWriter();
159
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
163
jsonWriter.WriteStartArray();
164
jsonWriter.WriteValue((object)value);
165
jsonWriter.WriteEndArray();
168
string json = sw.ToString();
169
string expected = @"[""c""]";
171
Assert.AreEqual(expected, json);
175
public void WriteValueObjectWithUnsupportedValue()
177
ExceptionAssert.Throws<JsonWriterException>(
178
@"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.",
181
StringWriter sw = new StringWriter();
182
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
184
jsonWriter.WriteStartArray();
185
jsonWriter.WriteValue(new Version(1, 1, 1, 1));
186
jsonWriter.WriteEndArray();
192
public void StringEscaping()
194
StringBuilder sb = new StringBuilder();
195
StringWriter sw = new StringWriter(sb);
197
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
199
jsonWriter.WriteStartArray();
200
jsonWriter.WriteValue(@"""These pretzels are making me thirsty!""");
201
jsonWriter.WriteValue("Jeff's house was burninated.");
202
jsonWriter.WriteValue(@"1. You don't talk about fight club.
203
2. You don't talk about fight club.");
204
jsonWriter.WriteValue("35% of\t statistics\n are made\r up.");
205
jsonWriter.WriteEndArray();
208
string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]";
209
string result = sb.ToString();
211
Console.WriteLine("StringEscaping");
212
Console.WriteLine(result);
214
Assert.AreEqual(expected, result);
218
public void WriteEnd()
220
StringBuilder sb = new StringBuilder();
221
StringWriter sw = new StringWriter(sb);
223
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
225
jsonWriter.Formatting = Formatting.Indented;
227
jsonWriter.WriteStartObject();
228
jsonWriter.WritePropertyName("CPU");
229
jsonWriter.WriteValue("Intel");
230
jsonWriter.WritePropertyName("PSU");
231
jsonWriter.WriteValue("500W");
232
jsonWriter.WritePropertyName("Drives");
233
jsonWriter.WriteStartArray();
234
jsonWriter.WriteValue("DVD read/writer");
235
jsonWriter.WriteComment("(broken)");
236
jsonWriter.WriteValue("500 gigabyte hard drive");
237
jsonWriter.WriteValue("200 gigabype hard drive");
238
jsonWriter.WriteEndObject();
239
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
242
string expected = @"{
248
""500 gigabyte hard drive"",
249
""200 gigabype hard drive""
252
string result = sb.ToString();
254
Assert.AreEqual(expected, result);
258
public void CloseWithRemainingContent()
260
StringBuilder sb = new StringBuilder();
261
StringWriter sw = new StringWriter(sb);
263
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
265
jsonWriter.Formatting = Formatting.Indented;
267
jsonWriter.WriteStartObject();
268
jsonWriter.WritePropertyName("CPU");
269
jsonWriter.WriteValue("Intel");
270
jsonWriter.WritePropertyName("PSU");
271
jsonWriter.WriteValue("500W");
272
jsonWriter.WritePropertyName("Drives");
273
jsonWriter.WriteStartArray();
274
jsonWriter.WriteValue("DVD read/writer");
275
jsonWriter.WriteComment("(broken)");
276
jsonWriter.WriteValue("500 gigabyte hard drive");
277
jsonWriter.WriteValue("200 gigabype hard drive");
281
string expected = @"{
287
""500 gigabyte hard drive"",
288
""200 gigabype hard drive""
291
string result = sb.ToString();
293
Assert.AreEqual(expected, result);
297
public void Indenting()
299
StringBuilder sb = new StringBuilder();
300
StringWriter sw = new StringWriter(sb);
302
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
304
jsonWriter.Formatting = Formatting.Indented;
306
jsonWriter.WriteStartObject();
307
jsonWriter.WritePropertyName("CPU");
308
jsonWriter.WriteValue("Intel");
309
jsonWriter.WritePropertyName("PSU");
310
jsonWriter.WriteValue("500W");
311
jsonWriter.WritePropertyName("Drives");
312
jsonWriter.WriteStartArray();
313
jsonWriter.WriteValue("DVD read/writer");
314
jsonWriter.WriteComment("(broken)");
315
jsonWriter.WriteValue("500 gigabyte hard drive");
316
jsonWriter.WriteValue("200 gigabype hard drive");
317
jsonWriter.WriteEnd();
318
jsonWriter.WriteEndObject();
319
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
328
// "500 gigabyte hard drive",
329
// "200 gigabype hard drive"
333
string expected = @"{
339
""500 gigabyte hard drive"",
340
""200 gigabype hard drive""
343
string result = sb.ToString();
345
Assert.AreEqual(expected, result);
351
StringBuilder sb = new StringBuilder();
352
StringWriter sw = new StringWriter(sb);
354
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
356
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
358
jsonWriter.WriteStartObject();
359
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
360
Assert.AreEqual("", jsonWriter.Path);
362
jsonWriter.WritePropertyName("CPU");
363
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
364
Assert.AreEqual("CPU", jsonWriter.Path);
366
jsonWriter.WriteValue("Intel");
367
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
368
Assert.AreEqual("CPU", jsonWriter.Path);
370
jsonWriter.WritePropertyName("Drives");
371
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
372
Assert.AreEqual("Drives", jsonWriter.Path);
374
jsonWriter.WriteStartArray();
375
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
377
jsonWriter.WriteValue("DVD read/writer");
378
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
379
Assert.AreEqual("Drives[0]", jsonWriter.Path);
381
jsonWriter.WriteEnd();
382
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
383
Assert.AreEqual("Drives", jsonWriter.Path);
385
jsonWriter.WriteEndObject();
386
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
387
Assert.AreEqual("", jsonWriter.Path);
392
public void FloatingPointNonFiniteNumbers()
394
StringBuilder sb = new StringBuilder();
395
StringWriter sw = new StringWriter(sb);
397
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
399
jsonWriter.Formatting = Formatting.Indented;
401
jsonWriter.WriteStartArray();
402
jsonWriter.WriteValue(double.NaN);
403
jsonWriter.WriteValue(double.PositiveInfinity);
404
jsonWriter.WriteValue(double.NegativeInfinity);
405
jsonWriter.WriteValue(float.NaN);
406
jsonWriter.WriteValue(float.PositiveInfinity);
407
jsonWriter.WriteValue(float.NegativeInfinity);
408
jsonWriter.WriteEndArray();
413
string expected = @"[
421
string result = sb.ToString();
423
Assert.AreEqual(expected, result);
427
public void WriteRawInStart()
429
StringBuilder sb = new StringBuilder();
430
StringWriter sw = new StringWriter(sb);
432
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
434
jsonWriter.Formatting = Formatting.Indented;
436
jsonWriter.WriteRaw("[1,2,3,4,5]");
437
jsonWriter.WriteWhitespace(" ");
438
jsonWriter.WriteStartArray();
439
jsonWriter.WriteValue(double.NaN);
440
jsonWriter.WriteEndArray();
443
string expected = @"[1,2,3,4,5] [
446
string result = sb.ToString();
448
Assert.AreEqual(expected, result);
452
public void WriteRawInArray()
454
StringBuilder sb = new StringBuilder();
455
StringWriter sw = new StringWriter(sb);
457
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
459
jsonWriter.Formatting = Formatting.Indented;
461
jsonWriter.WriteStartArray();
462
jsonWriter.WriteValue(double.NaN);
463
jsonWriter.WriteRaw(",[1,2,3,4,5]");
464
jsonWriter.WriteRaw(",[1,2,3,4,5]");
465
jsonWriter.WriteValue(float.NaN);
466
jsonWriter.WriteEndArray();
469
string expected = @"[
470
NaN,[1,2,3,4,5],[1,2,3,4,5],
473
string result = sb.ToString();
475
Assert.AreEqual(expected, result);
479
public void WriteRawInObject()
481
StringBuilder sb = new StringBuilder();
482
StringWriter sw = new StringWriter(sb);
484
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
486
jsonWriter.Formatting = Formatting.Indented;
488
jsonWriter.WriteStartObject();
489
jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]");
490
jsonWriter.WriteEnd();
493
string expected = @"{""PropertyName"":[1,2,3,4,5]}";
494
string result = sb.ToString();
496
Assert.AreEqual(expected, result);
500
public void WriteToken()
502
JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]"));
506
StringWriter sw = new StringWriter();
507
JsonTextWriter writer = new JsonTextWriter(sw);
508
writer.WriteToken(reader);
510
Assert.AreEqual("1", sw.ToString());
514
public void WriteRawValue()
516
StringBuilder sb = new StringBuilder();
517
StringWriter sw = new StringWriter(sb);
519
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
522
string rawJson = "[1,2]";
524
jsonWriter.WriteStartObject();
528
jsonWriter.WritePropertyName("d" + i);
529
jsonWriter.WriteRawValue(rawJson);
534
jsonWriter.WriteEndObject();
537
Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString());
541
public void WriteObjectNestedInConstructor()
543
StringBuilder sb = new StringBuilder();
544
StringWriter sw = new StringWriter(sb);
546
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
548
jsonWriter.WriteStartObject();
549
jsonWriter.WritePropertyName("con");
551
jsonWriter.WriteStartConstructor("Ext.data.JsonStore");
552
jsonWriter.WriteStartObject();
553
jsonWriter.WritePropertyName("aa");
554
jsonWriter.WriteValue("aa");
555
jsonWriter.WriteEndObject();
556
jsonWriter.WriteEndConstructor();
558
jsonWriter.WriteEndObject();
561
Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString());
565
public void WriteFloatingPointNumber()
567
StringBuilder sb = new StringBuilder();
568
StringWriter sw = new StringWriter(sb);
570
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
572
jsonWriter.WriteStartArray();
574
jsonWriter.WriteValue(0.0);
575
jsonWriter.WriteValue(0f);
576
jsonWriter.WriteValue(0.1);
577
jsonWriter.WriteValue(1.0);
578
jsonWriter.WriteValue(1.000001);
579
jsonWriter.WriteValue(0.000001);
580
jsonWriter.WriteValue(double.Epsilon);
581
jsonWriter.WriteValue(double.PositiveInfinity);
582
jsonWriter.WriteValue(double.NegativeInfinity);
583
jsonWriter.WriteValue(double.NaN);
584
jsonWriter.WriteValue(double.MaxValue);
585
jsonWriter.WriteValue(double.MinValue);
586
jsonWriter.WriteValue(float.PositiveInfinity);
587
jsonWriter.WriteValue(float.NegativeInfinity);
588
jsonWriter.WriteValue(float.NaN);
590
jsonWriter.WriteEndArray();
593
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
597
public void BadWriteEndArray()
599
ExceptionAssert.Throws<JsonWriterException>(
600
"No token to close. Path ''.",
603
StringBuilder sb = new StringBuilder();
604
StringWriter sw = new StringWriter(sb);
606
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
608
jsonWriter.WriteStartArray();
610
jsonWriter.WriteValue(0.0);
612
jsonWriter.WriteEndArray();
613
jsonWriter.WriteEndArray();
619
public void InvalidQuoteChar()
621
ExceptionAssert.Throws<ArgumentException>(
622
@"Invalid JavaScript string quote character. Valid quote characters are ' and "".",
625
StringBuilder sb = new StringBuilder();
626
StringWriter sw = new StringWriter(sb);
628
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
630
jsonWriter.Formatting = Formatting.Indented;
631
jsonWriter.QuoteChar = '*';
637
public void Indentation()
639
StringBuilder sb = new StringBuilder();
640
StringWriter sw = new StringWriter(sb);
642
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
644
jsonWriter.Formatting = Formatting.Indented;
645
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
647
jsonWriter.Indentation = 5;
648
Assert.AreEqual(5, jsonWriter.Indentation);
649
jsonWriter.IndentChar = '_';
650
Assert.AreEqual('_', jsonWriter.IndentChar);
651
jsonWriter.QuoteName = true;
652
Assert.AreEqual(true, jsonWriter.QuoteName);
653
jsonWriter.QuoteChar = '\'';
654
Assert.AreEqual('\'', jsonWriter.QuoteChar);
656
jsonWriter.WriteStartObject();
657
jsonWriter.WritePropertyName("propertyName");
658
jsonWriter.WriteValue(double.NaN);
659
jsonWriter.WriteEndObject();
662
string expected = @"{
663
_____'propertyName': NaN
665
string result = sb.ToString();
667
Assert.AreEqual(expected, result);
671
public void WriteSingleBytes()
673
StringBuilder sb = new StringBuilder();
674
StringWriter sw = new StringWriter(sb);
676
string text = "Hello world.";
677
byte[] data = Encoding.UTF8.GetBytes(text);
679
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
681
jsonWriter.Formatting = Formatting.Indented;
682
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
684
jsonWriter.WriteValue(data);
687
string expected = @"""SGVsbG8gd29ybGQu""";
688
string result = sb.ToString();
690
Assert.AreEqual(expected, result);
692
byte[] d2 = Convert.FromBase64String(result.Trim('"'));
694
Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length));
698
public void WriteBytesInArray()
700
StringBuilder sb = new StringBuilder();
701
StringWriter sw = new StringWriter(sb);
703
string text = "Hello world.";
704
byte[] data = Encoding.UTF8.GetBytes(text);
706
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
708
jsonWriter.Formatting = Formatting.Indented;
709
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
711
jsonWriter.WriteStartArray();
712
jsonWriter.WriteValue(data);
713
jsonWriter.WriteValue(data);
714
jsonWriter.WriteValue((object)data);
715
jsonWriter.WriteValue((byte[])null);
716
jsonWriter.WriteValue((Uri)null);
717
jsonWriter.WriteEndArray();
720
string expected = @"[
721
""SGVsbG8gd29ybGQu"",
722
""SGVsbG8gd29ybGQu"",
723
""SGVsbG8gd29ybGQu"",
727
string result = sb.ToString();
729
Assert.AreEqual(expected, result);
735
StringBuilder sb = new StringBuilder();
736
StringWriter sw = new StringWriter(sb);
738
string text = "Hello world.";
739
byte[] data = Encoding.UTF8.GetBytes(text);
741
using (JsonTextWriter writer = new JsonTextWriter(sw))
743
writer.Formatting = Formatting.Indented;
745
writer.WriteStartArray();
746
Assert.AreEqual("", writer.Path);
747
writer.WriteStartObject();
748
Assert.AreEqual("[0]", writer.Path);
749
writer.WritePropertyName("Property1");
750
Assert.AreEqual("[0].Property1", writer.Path);
751
writer.WriteStartArray();
752
Assert.AreEqual("[0].Property1", writer.Path);
753
writer.WriteValue(1);
754
Assert.AreEqual("[0].Property1[0]", writer.Path);
755
writer.WriteStartArray();
756
Assert.AreEqual("[0].Property1[1]", writer.Path);
757
writer.WriteStartArray();
758
Assert.AreEqual("[0].Property1[1][0]", writer.Path);
759
writer.WriteStartArray();
760
Assert.AreEqual("[0].Property1[1][0][0]", writer.Path);
761
writer.WriteEndObject();
762
Assert.AreEqual("[0]", writer.Path);
763
writer.WriteStartObject();
764
Assert.AreEqual("[1]", writer.Path);
765
writer.WritePropertyName("Property2");
766
Assert.AreEqual("[1].Property2", writer.Path);
767
writer.WriteStartConstructor("Constructor1");
768
Assert.AreEqual("[1].Property2", writer.Path);
770
Assert.AreEqual("[1].Property2[0]", writer.Path);
771
writer.WriteStartArray();
772
Assert.AreEqual("[1].Property2[1]", writer.Path);
773
writer.WriteValue(1);
774
Assert.AreEqual("[1].Property2[1][0]", writer.Path);
776
Assert.AreEqual("[1].Property2[1]", writer.Path);
777
writer.WriteEndObject();
778
Assert.AreEqual("[1]", writer.Path);
779
writer.WriteEndArray();
780
Assert.AreEqual("", writer.Path);
795
""Property2"": new Constructor1(
806
public void BuildStateArray()
808
JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray();
810
var valueStates = JsonWriter.StateArrayTempate[7];
812
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
816
case JsonToken.Integer:
817
case JsonToken.Float:
818
case JsonToken.String:
819
case JsonToken.Boolean:
821
case JsonToken.Undefined:
823
case JsonToken.Bytes:
824
Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states.");
831
public void DateTimeZoneHandling()
833
StringWriter sw = new StringWriter();
834
JsonTextWriter writer = new JsonTextWriter(sw)
836
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
839
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
841
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString());
845
public void HtmlStringEscapeHandling()
847
StringWriter sw = new StringWriter();
848
JsonTextWriter writer = new JsonTextWriter(sw)
850
StringEscapeHandling = StringEscapeHandling.EscapeHtml
853
string script = @"<script type=""text/javascript"">alert('hi');</script>";
855
writer.WriteValue(script);
857
string json = sw.ToString();
859
Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json);
861
JsonTextReader reader = new JsonTextReader(new StringReader(json));
863
Assert.AreEqual(script, reader.ReadAsString());
865
//Console.WriteLine(HttpUtility.HtmlEncode(script));
867
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
868
//Console.WriteLine(s.Serialize(new { html = script }));
872
public void NonAsciiStringEscapeHandling()
874
StringWriter sw = new StringWriter();
875
JsonTextWriter writer = new JsonTextWriter(sw)
877
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
880
string unicode = "\u5f20";
882
writer.WriteValue(unicode);
884
string json = sw.ToString();
886
Assert.AreEqual(8, json.Length);
887
Assert.AreEqual(@"""\u5f20""", json);
889
JsonTextReader reader = new JsonTextReader(new StringReader(json));
891
Assert.AreEqual(unicode, reader.ReadAsString());
893
sw = new StringWriter();
894
writer = new JsonTextWriter(sw)
896
StringEscapeHandling = StringEscapeHandling.Default
899
writer.WriteValue(unicode);
901
json = sw.ToString();
903
Assert.AreEqual(3, json.Length);
904
Assert.AreEqual("\"\u5f20\"", json);
908
public void WriteEndOnProperty()
910
StringWriter sw = new StringWriter();
911
JsonTextWriter writer = new JsonTextWriter(sw);
912
writer.QuoteChar = '\'';
914
writer.WriteStartObject();
915
writer.WritePropertyName("Blah");
918
Assert.AreEqual("{'Blah':null}", sw.ToString());
923
public void QuoteChar()
925
StringWriter sw = new StringWriter();
926
JsonTextWriter writer = new JsonTextWriter(sw);
927
writer.Formatting = Formatting.Indented;
928
writer.QuoteChar = '\'';
930
writer.WriteStartArray();
932
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
933
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
935
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
936
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
937
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
939
writer.WriteValue(new byte[] { 1, 2, 3 });
940
writer.WriteValue(TimeSpan.Zero);
941
writer.WriteValue(new Uri("http://www.google.com/"));
942
writer.WriteValue(Guid.Empty);
947
'2000-01-01T01:01:01Z',
948
'2000-01-01T01:01:01+00:00',
949
'\/Date(946688461000)\/',
950
'\/Date(946688461000+0000)\/',
953
'http://www.google.com/',
954
'00000000-0000-0000-0000-000000000000'
960
public void CompareNewStringEscapingWithOld()
962
Console.WriteLine("Started");
969
Console.WriteLine("Position: " + (int)c);
971
StringWriter swNew = new StringWriter();
972
JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default);
974
StringWriter swOld = new StringWriter();
975
WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true);
977
string newText = swNew.ToString();
978
string oldText = swOld.ToString();
980
if (newText != oldText)
981
throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int) c, oldText, newText));
984
} while (c != char.MaxValue);
986
Console.WriteLine("Finished");
989
private const string EscapedUnicodeText = "!";
991
private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters)
994
if (appendDelimiters)
995
writer.Write(delimiter);
1000
char[] unicodeBuffer = null;
1001
int lastWritePosition = 0;
1003
for (int i = 0; i < s.Length; i++)
1007
// don't escape standard text/numbers except '\' and the text delimiter
1008
if (c >= ' ' && c < 128 && c != '\\' && c != delimiter)
1011
string escapedValue;
1016
escapedValue = @"\t";
1019
escapedValue = @"\n";
1022
escapedValue = @"\r";
1025
escapedValue = @"\f";
1028
escapedValue = @"\b";
1031
escapedValue = @"\\";
1033
case '\u0085': // Next Line
1034
escapedValue = @"\u0085";
1036
case '\u2028': // Line Separator
1037
escapedValue = @"\u2028";
1039
case '\u2029': // Paragraph Separator
1040
escapedValue = @"\u2029";
1043
// this charater is being used as the delimiter
1044
escapedValue = @"\'";
1047
// this charater is being used as the delimiter
1048
escapedValue = "\\\"";
1053
if (unicodeBuffer == null)
1054
unicodeBuffer = new char[6];
1056
StringUtils.ToCharAsUnicode(c, unicodeBuffer);
1058
// slightly hacky but it saves multiple conditions in if test
1059
escapedValue = EscapedUnicodeText;
1063
escapedValue = null;
1068
if (escapedValue == null)
1071
if (i > lastWritePosition)
1074
chars = s.ToCharArray();
1076
// write unchanged chars before writing escaped text
1077
writer.Write(chars, lastWritePosition, i - lastWritePosition);
1080
lastWritePosition = i + 1;
1081
if (!string.Equals(escapedValue, EscapedUnicodeText))
1082
writer.Write(escapedValue);
1084
writer.Write(unicodeBuffer);
1087
if (lastWritePosition == 0)
1089
// no escaped text, write entire string
1095
chars = s.ToCharArray();
1097
// write remaining text
1098
writer.Write(chars, lastWritePosition, s.Length - lastWritePosition);
1102
// trailing delimiter
1103
if (appendDelimiters)
1104
writer.Write(delimiter);
b'\\ No newline at end of file'