forked from dotnet/corefx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWriteValueTests.cs
72 lines (58 loc) · 2.68 KB
/
WriteValueTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class WriteValueTests
{
[Fact]
public static void NullWriterThrows()
{
Assert.Throws<ArgumentNullException>(() => JsonSerializer.Serialize(null, 1));
Assert.Throws<ArgumentNullException>(() => JsonSerializer.Serialize(null, 1, typeof(int)));
}
[Fact]
public static void CanWriteValueToJsonArray()
{
using MemoryStream memoryStream = new MemoryStream();
using Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream);
writer.WriteStartObject();
writer.WriteStartArray("test");
JsonSerializer.Serialize<int>(writer, 1);
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
string json = Encoding.UTF8.GetString(memoryStream.ToArray());
Assert.Equal("{\"test\":[1]}", json);
}
public class CustomClassWithEscapedProperty
{
public int pizza { get; set; }
public int hello\u6C49\u5B57 { get; set; }
public int normal { get; set; }
}
[Fact]
public static void SerializeToWriterRoundTripEscaping()
{
const string jsonIn = " { \"p\\u0069zza\": 1, \"hello\\u6C49\\u5B57\": 2, \"normal\": 3 }";
CustomClassWithEscapedProperty input = JsonSerializer.Deserialize<CustomClassWithEscapedProperty>(jsonIn);
Assert.Equal(1, input.pizza);
Assert.Equal(2, input.hello\u6C49\u5B57);
Assert.Equal(3, input.normal);
string normalizedString = JsonSerializer.Serialize(input);
Assert.Equal("{\"pizza\":1,\"hello\\u6C49\\u5B57\":2,\"normal\":3}", normalizedString);
CustomClassWithEscapedProperty inputNormalized = JsonSerializer.Deserialize<CustomClassWithEscapedProperty>(normalizedString);
Assert.Equal(1, inputNormalized.pizza);
Assert.Equal(2, inputNormalized.hello\u6C49\u5B57);
Assert.Equal(3, inputNormalized.normal);
using MemoryStream memoryStream = new MemoryStream();
using Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream);
JsonSerializer.Serialize(writer, inputNormalized);
writer.Flush();
string json = Encoding.UTF8.GetString(memoryStream.ToArray());
Assert.Equal(normalizedString, json);
}
}
}