You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+194-1Lines changed: 194 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -54,6 +54,8 @@ JSON payload without it's concrete type, see these real-world examples:
54
54
For reasons outlined [in this blog post](http://www.servicestack.net/mythz_blog/?p=344) I decided to re-use *TypeSerializer's* text processing-core to create ServiceStack.JsonSerializer - the fastest JSON Serializer for .NET.
55
55
Based on the [Northwind Benchmarks](http://www.servicestack.net/benchmarks/NorthwindDatabaseRowsSerialization.100000-times.2010-08-17.html) it's *3.6x* faster than .NET's BCL JsonDataContractSerializer and *3x* faster then the previous fastest JSON serializer benchmarked - [JSON.NET](http://json.codeplex.com/).
56
56
57
+
A comprehensive list of benchmarks are maintained at [servicestack.net/benchmarks](http://http://www.servicestack.net/benchmarks).
58
+
57
59
## ServiceStack.CsvSerializer
58
60
As CSV is an important format in many data access and migration scenarios, it became [the latest format included in ServiceStack](https://github.com/ServiceStack/ServiceStack/wiki/ServiceStack-CSV-Format) which allows all your existing web services to take advantage of the new format without config or code-changes. As its built using the same tech that makes the JSON and JSV serializers so fast, we expect it to be the fastest POCO CSV Serializer for .NET.
59
61
@@ -100,7 +102,198 @@ Another useful library to have in your .NET toolbox is the [T.Dump() Extension M
100
102
101
103
<hr />
102
104
103
-
#TypeSerializer Details
105
+
# ServiceStack's JsonSerializer
106
+
107
+
ServiceStack's JsonSerializer is optimized for serializing C# POCO types in and out of JSON as fast, compact and cleanly as possible. In most cases C# objects serializes as you would expect them to without added json extensions or serializer-specific artefacts.
108
+
109
+
JsonSerializer provides a simple API that allows you to serialize any .NET generic or runtime type into a string, TextWriter/TextReader or Stream.
110
+
111
+
### Serialization API
112
+
113
+
string SerializeToString<T>(T)
114
+
void SerializeToWriter<T>(T, TextWriter)
115
+
void SerializeToStream<T>(T, Stream)
116
+
string SerializeToString(object, Type)
117
+
void SerializeToWriter(object, Type, TextWriter)
118
+
void SerializeToStream(object, Type, Stream)
119
+
120
+
### Deserialization API
121
+
122
+
T DeserializeFromString<T>(string)
123
+
T DeserializeFromReader<T>(TextReader)
124
+
object DeserializeFromString(string, Type)
125
+
object DeserializeFromReader(reader, Type)
126
+
object DeserializeFromStream(Type, Stream)
127
+
T DeserializeFromStream<T>(Stream)
128
+
129
+
### Extension methods
130
+
131
+
string ToJson<T>(this T)
132
+
T FromJson<T>(this string)
133
+
134
+
Convenient **ToJson/FromJson** extension methods are also included reducing the amount of code required, e.g:
135
+
136
+
new []{ 1, 2, 3 }.ToJson() //= [1,2,3]
137
+
"[1,2,3]".FromJson<int[]>() //= int []{ 1, 2, 3 }
138
+
139
+
## JSON Format
140
+
141
+
JSON is a lightweight text serialization format with a spec that's so simple that it fits on one page: [http://www.json.org](json.org).
142
+
143
+
The only valid values in JSON are:
144
+
145
+
* string
146
+
* number
147
+
* object
148
+
* array
149
+
* true
150
+
* false
151
+
* null
152
+
153
+
Where most allowed values are scalar and the only complex types available are objects and arrays. Although limited, the above set of types make a good fit and can express most programming data structures.
154
+
155
+
### number, true, false types
156
+
157
+
All C# boolean and numeric data types are stored as-is without quotes.
158
+
159
+
### null type
160
+
161
+
For the most compact output null values are omitted from the serialized by default. If you want to include null values set the global configuration:
162
+
163
+
JsConfig.IncludeNullValues = true;
164
+
165
+
### string type
166
+
167
+
All other scalar values are stored as strings that are surrounded with double quotes.
168
+
169
+
### C# Structs and Value Types
170
+
171
+
Because a C# struct is a value type whose public properties are normally just convenience properties around a single scalar value, they are ignored instead the **TStruct.ToString()** method is used to serialize and either the **static TStruct.Parse()** method or **new TStruct(string)** constructor will be used to deserialize the value type if it exists.
172
+
173
+
### array type
174
+
175
+
Any List, Queue, Stack, Array, Collection, Enumerables including custom enumerable types are stored in exactly the same way as a JavaScript array literal, i.e:
176
+
177
+
[1,2,3,4,5]
178
+
179
+
All elements in an array must be of the same type. If a custom type is both an IEnumerable and has properties it will be treated as an array and the extra properties will be ignored.
180
+
181
+
### object type
182
+
183
+
The JSON object type is the most flexible and is how most complex .NET types are serialized. The JSON object type is a key-value pair JavaScript object literal where the key is always a double-quoted string.
184
+
185
+
Any IDictionary is serialized into a standard JSON object, i.e:
186
+
187
+
{"A":1,"B":2,"C":3,"D":4}
188
+
189
+
Which happens to be the same as C# POCO types (inc. Interfaces) with the values:
190
+
191
+
`new MyClass { A=1, B=2, C=3, D=4 }`
192
+
193
+
{"A":1,"B":2,"C":3,"D":4}
194
+
195
+
Only public properties on reference types are serialized with the C# Property Name used for object key and the Property Value as the value. At the moment it is not possible to customize the Property Name.
196
+
197
+
JsonSerializer also supports serialization of anonymous types in much the same way:
198
+
199
+
`new { A=1, B=2, C=3, D=4 }`
200
+
201
+
{"A":1,"B":2,"C":3,"D":4}
202
+
203
+
204
+
## Custom Serialization
205
+
206
+
Although JsonSerializer is optimized for serializing .NET POCO types, it still provides some options to change the convention-based serialization routine.
207
+
208
+
### Using Structs to Customize JSON
209
+
210
+
This makes it possible to customize the serialization routine and provide an even more compact wire format.
211
+
212
+
E.g. Instead of using a JSON object to represent a point
213
+
214
+
{ Width=20, Height=10 }
215
+
216
+
You could use a struct and reduce it to just:
217
+
218
+
"20x10"
219
+
220
+
By overriding **ToString()** and providing a static **Size Parse()** method:
221
+
222
+
public struct Size
223
+
{
224
+
public double Width { get; set; }
225
+
public double Height { get; set; }
226
+
227
+
public override string ToString()
228
+
{
229
+
return Width + "x" + Height;
230
+
}
231
+
232
+
public static Size Parse(string json)
233
+
{
234
+
var size = json.Split('x');
235
+
return new Size {
236
+
Width = double.Parse(size[0]),
237
+
Height = double.Parse(size[1])
238
+
};
239
+
}
240
+
}
241
+
242
+
Which would change it to the more compact JSON output:
That allows you to deserialize it back in the same way:
247
+
248
+
var size = "20x10".FromJson<Size>();
249
+
250
+
### Using Custom IEnumerable class to serialize a JSON array
251
+
252
+
In addition to using a Struct you can optionally use a custom C# IEnumerable type to provide a strong-typed wrapper around a JSON array:
253
+
254
+
public class Point : IEnumerable
255
+
{
256
+
double[] points = new double[2];
257
+
258
+
public double X
259
+
{
260
+
get { return points[0]; }
261
+
set { points[0] = value; }
262
+
}
263
+
264
+
public double Y
265
+
{
266
+
get { return points[1]; }
267
+
set { points[1] = value; }
268
+
}
269
+
270
+
public IEnumerator GetEnumerator()
271
+
{
272
+
foreach (var point in points)
273
+
yield return point;
274
+
}
275
+
}
276
+
277
+
Which serializes the Point into a compact JSON array:
278
+
279
+
new Point { X = 1, Y = 2 }.ToJson() // = [1,2]
280
+
281
+
## Custom Deserialization
282
+
283
+
Because the same wire format shared between Dictionaries, POCOs and anonymous types, in most cases what you serialize with one type can be deserialized with another, i.e. an Anonymous type can be deserialized back into a Dictionary<string,string> which can be deserialized into a strong-typed POCO and vice-versa.
284
+
285
+
Although the JSON Serializer is best optimized for serializing and deserializing .NET types, it's flexible enough to consume 3rd party JSON apis although this generally requires custom de-serialization to convert it into an idiomatic .NET type.
1. Using [JsonObject](https://github.com/ServiceStack/ServiceStack.Text/blob/master/src/ServiceStack.Text/JsonObject.cs)
290
+
2. Using Generic .NET Collection classes
291
+
3. Using Customized DTO's in the shape of the 3rd party JSON response
292
+
293
+
[CentroidTests](https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/UseCases/CentroidTests.cs) is another example that uses the JsonObject to parse a complex custom JSON response.
294
+
295
+
296
+
#TypeSerializer Details (JSV Format)
104
297
105
298
Out of the box .NET provides a fairly quick but verbose Xml DataContractSerializer or a slightly more compact but slower JsonDataContractSerializer.
106
299
Both of these options are fragile and likely to break with any significant schema changes.
0 commit comments