forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeSerializer.Generic.cs
More file actions
68 lines (60 loc) · 1.47 KB
/
TypeSerializer.Generic.cs
File metadata and controls
68 lines (60 loc) · 1.47 KB
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
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.IO;
using System.Text;
using ServiceStack.Text.Jsv;
namespace ServiceStack.Text
{
public class TypeSerializer<T> : ITypeSerializer<T>
{
public bool CanCreateFromString(Type type)
{
return JsvReader.GetParseFn(type) != null;
}
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public T DeserializeFromString(string value)
{
if (string.IsNullOrEmpty(value)) return default(T);
return (T)JsvReader<T>.Parse(value);
}
public T DeserializeFromReader(TextReader reader)
{
return DeserializeFromString(reader.ReadToEnd());
}
public string SerializeToString(T value)
{
if (value == null) return null;
if (typeof(T) == typeof(string)) return value as string;
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
JsvWriter<T>.WriteObject(writer, value);
}
return sb.ToString();
}
public void SerializeToWriter(T value, TextWriter writer)
{
if (value == null) return;
if (typeof(T) == typeof(string))
{
writer.Write(value);
return;
}
JsvWriter<T>.WriteObject(writer, value);
}
}
}