TestOptions.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Topten.JsonKit;
  6. using System.Reflection;
  7. using Xunit;
  8. namespace TestCases
  9. {
  10. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  11. public class TestOptions
  12. {
  13. [Fact]
  14. public void TestWhitespace()
  15. {
  16. var o = new { x = 10, y = 20 };
  17. var json = Json.Format(o, JsonOptions.WriteWhitespace);
  18. Assert.Contains("\n", json);
  19. Assert.Contains("\t", json);
  20. Assert.Contains(": ", json);
  21. json = Json.Format(o, JsonOptions.DontWriteWhitespace);
  22. Assert.DoesNotContain("\n", json);
  23. Assert.DoesNotContain("\t", json);
  24. Assert.DoesNotContain(": ", json);
  25. }
  26. [Fact]
  27. public void TestStrictComments()
  28. {
  29. var jsonWithCComment = "/* This is a comment*/ 23";
  30. var jsonWithCppComment = "// This is a comment\n 23";
  31. // Nonstrict parser allows it
  32. var val = Json.Parse<int>(jsonWithCComment, JsonOptions.NonStrictParser);
  33. Assert.Equal(23, val);
  34. val = Json.Parse<int>(jsonWithCppComment, JsonOptions.NonStrictParser);
  35. Assert.Equal(23, val);
  36. // Strict parser
  37. Assert.Throws<JsonParseException>(() => Json.Parse<int>(jsonWithCComment, JsonOptions.StrictParser));
  38. Assert.Throws<JsonParseException>(() => Json.Parse<int>(jsonWithCppComment, JsonOptions.StrictParser));
  39. }
  40. [Fact]
  41. public void TestStrictTrailingCommas()
  42. {
  43. var arrayWithTrailingComma = "[1,2,]";
  44. var dictWithTrailingComma = "{\"a\":1,\"b\":2,}";
  45. // Nonstrict parser allows it
  46. var array = Json.Parse<int[]>(arrayWithTrailingComma, JsonOptions.NonStrictParser);
  47. Assert.Equal(2, array.Length);
  48. var dict = Json.Parse<IDictionary<string, object>>(dictWithTrailingComma, JsonOptions.NonStrictParser);
  49. Assert.Equal(2, dict.Count);
  50. // Strict parser
  51. Assert.Throws<JsonParseException>(() => Json.Parse<int>(arrayWithTrailingComma, JsonOptions.StrictParser));
  52. Assert.Throws<JsonParseException>(() => Json.Parse<int>(dictWithTrailingComma, JsonOptions.StrictParser));
  53. }
  54. [Fact]
  55. public void TestStrictIdentifierKeys()
  56. {
  57. var data = "{a:1,b:2}";
  58. var dict = Json.Parse<IDictionary<string, object>>(data, JsonOptions.NonStrictParser);
  59. Assert.Equal(2, dict.Count);
  60. Assert.Contains("a", dict.Keys);
  61. Assert.Contains("b", dict.Keys);
  62. Assert.Throws<JsonParseException>(() => Json.Parse<Dictionary<string, object>>(data, JsonOptions.StrictParser));
  63. }
  64. }
  65. }