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

Commit 452c1f9

Browse files
committed
Add test for showing RawSerializeFn behavior of types.
1 parent f080ba2 commit 452c1f9

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,5 +87,81 @@ public void Can_override_Guid_serialization_format()
8787
Assert.That(guid.ToJson().Trim('"'), Is.EqualTo("adfa988b-01f6-490d-b65b-63750f869496"));
8888
Assert.That(guid.ToJsv(), Is.EqualTo("adfa988b-01f6-490d-b65b-63750f869496"));
8989
}
90+
91+
public class Parent
92+
{
93+
public ICar Car { get; set; }
94+
}
95+
96+
public interface ICar
97+
{
98+
string CarType { get; }
99+
}
100+
101+
public class LuxaryCar : ICar
102+
{
103+
public string Sunroof { get; set; }
104+
105+
public string CarType { get { return "Luxary"; } }
106+
}
107+
108+
public class CheapCar : ICar
109+
{
110+
public bool HasCupHolder { get; set; }
111+
112+
public string CarType { get { return "Cheap"; } }
113+
}
114+
115+
[Test]
116+
public void Does_call_RawSerializeFn_for_toplevel_types()
117+
{
118+
JsConfig<ICar>.RawSerializeFn = SerializeCar;
119+
120+
var luxaryParent = new Parent() { Car = new LuxaryCar() { Sunroof = "Big" } };
121+
var cheapParent = new Parent() { Car = new CheapCar() { HasCupHolder = true } };
122+
123+
// Works when ICar is a child
124+
var luxaryParentJson = luxaryParent.ToJson();
125+
var cheapParentJson = cheapParent.ToJson();
126+
127+
Assert.That(luxaryParentJson, Is.Not.StringContaining("__type"));
128+
Assert.That(cheapParentJson, Is.Not.StringContaining("__type"));
129+
130+
ICar luxary = new LuxaryCar() { Sunroof = "Big" };
131+
ICar cheap = new CheapCar() { HasCupHolder = true };
132+
133+
// ToJson() loses runtime cast of interface type, to keep it we need to specify it on call-site
134+
var luxaryJson = JsonSerializer.SerializeToString(luxary, typeof(ICar));
135+
var cheapJson = JsonSerializer.SerializeToString(cheap, typeof(ICar));
136+
137+
Assert.That(luxaryJson, Is.Not.StringContaining("__type"));
138+
Assert.That(cheapJson, Is.Not.StringContaining("__type"));
139+
140+
JsConfig.Reset();
141+
}
142+
143+
private static string SerializeCar(ICar car)
144+
{
145+
var jsonObject = JsonObject.Parse(car.ToJson());
146+
147+
if (jsonObject.ContainsKey("__type"))
148+
jsonObject.Remove("__type");
149+
150+
return jsonObject.ToJson();
151+
}
152+
153+
[Test]
154+
public void Does_call_RawSerializeFn_for_toplevel_concrete_type()
155+
{
156+
JsConfig<LuxaryCar>.RawSerializeFn = c => "{\"foo\":1}";
157+
158+
ICar luxary = new LuxaryCar { Sunroof = "Big" };
159+
160+
var luxaryJson = luxary.ToJson();
161+
162+
Assert.That(luxaryJson, Is.StringContaining("foo"));
163+
164+
JsConfig.Reset();
165+
}
90166
}
91167
}

0 commit comments

Comments
 (0)