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

Commit 04bd32f

Browse files
committed
Fix JSV encoding to always encode strings
1 parent b07bd02 commit 04bd32f

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

src/ServiceStack.Text/TypeSerializer.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ public static string SerializeToString<T>(T value)
126126
public static string SerializeToString(object value, Type type)
127127
{
128128
if (value == null) return null;
129-
if (type == typeof(string))
130-
return value as string;
129+
if (value is string str)
130+
return str.EncodeJsv();
131131

132132
var writer = StringWriterThreadStatic.Allocate();
133133
JsvWriter.GetWriteFn(type)(writer, value);
@@ -137,9 +137,9 @@ public static string SerializeToString(object value, Type type)
137137
public static void SerializeToWriter<T>(T value, TextWriter writer)
138138
{
139139
if (value == null) return;
140-
if (typeof(T) == typeof(string))
140+
if (value is string str)
141141
{
142-
writer.Write(value);
142+
writer.Write(str.EncodeJsv());
143143
}
144144
else if (typeof(T) == typeof(object))
145145
{
@@ -160,9 +160,9 @@ public static void SerializeToWriter<T>(T value, TextWriter writer)
160160
public static void SerializeToWriter(object value, Type type, TextWriter writer)
161161
{
162162
if (value == null) return;
163-
if (type == typeof(string))
163+
if (value is string str)
164164
{
165-
writer.Write(value);
165+
writer.Write(str.EncodeJsv());
166166
return;
167167
}
168168

@@ -305,8 +305,7 @@ public static void Print(this long longValue)
305305

306306
public static string SerializeAndFormat<T>(this T instance)
307307
{
308-
var fn = instance as Delegate;
309-
if (fn != null)
308+
if (instance is Delegate fn)
310309
return Dump(fn);
311310

312311
var dtoStr = !HasCircularReferences(instance)

tests/ServiceStack.Text.Tests/JsvTests/JsvBasicDataTests.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,5 +102,14 @@ public void Can_serialize_ModelWithNullableFloatTypes_From_String()
102102
fromJsv = jsv.FromJsv<ModelWithNullableFloatTypes>();
103103
Assert.That(fromJsv, Is.EqualTo(dto));
104104
}
105+
106+
[Test]
107+
public void Does_encode_object_string_values_with_escaped_chars()
108+
{
109+
var url = "https://url.com";
110+
Assert.That(url.ToJsv(), Is.EqualTo("\"https://url.com\""));
111+
Assert.That(((object)url).ToJsv(), Is.EqualTo("\"https://url.com\""));
112+
}
113+
105114
}
106115
}

0 commit comments

Comments
 (0)