Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 5f24fea

Browse files
committed
Add Serialize to Hex example
1 parent ae99783 commit 5f24fea

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

tests/ServiceStack.Text.Tests/JsonTests/CustomRawSerializerTests.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Globalization;
3+
using System.Linq;
34
using NUnit.Framework;
45

56
namespace ServiceStack.Text.Tests.JsonTests
@@ -35,6 +36,37 @@ public void Can_Serialize_TypeProperties_WithCustomFunction()
3536

3637
// Assert:
3738
Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":[1,2,3,4,5]}"));
39+
40+
JsConfig.Reset();
41+
}
42+
43+
[Test]
44+
public void Can_Serialize_bytes_as_Hex()
45+
{
46+
JsConfig<byte[]>.SerializeFn = BitConverter.ToString;
47+
JsConfig<byte[]>.DeSerializeFn = hex =>
48+
{
49+
hex = hex.Replace("-", "");
50+
return Enumerable.Range(0, hex.Length)
51+
.Where(x => x%2 == 0)
52+
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
53+
.ToArray();
54+
};
55+
56+
var dto = new RealType
57+
{
58+
Name = "Red",
59+
Data = new byte[] { 255, 0, 0 }
60+
};
61+
62+
var json = dto.ToJson();
63+
Assert.That(json, Is.StringContaining("FF-00-00"));
64+
65+
var fromJson = json.FromJson<RealType>();
66+
67+
Assert.That(fromJson.Data, Is.EquivalentTo(dto.Data));
68+
69+
JsConfig.Reset();
3870
}
3971

4072
[Test]

0 commit comments

Comments
 (0)