2
// http://code.google.com/p/servicestack/wiki/TypeSerializer
3
// ServiceStack.Text: .NET C# POCO Type Text Serializer.
6
// Demis Bellot (demis.bellot@gmail.com)
8
// Copyright 2011 Liquidbit Ltd.
10
// Licensed under the same terms of ServiceStack: new BSD license.
16
using ServiceStack.Text.Common;
17
using ServiceStack.Text.Json;
19
namespace ServiceStack.Text
21
public class JsonSerializer<T> : ITypeSerializer<T>
23
public bool CanCreateFromString(Type type)
25
return JsonReader.GetParseFn(type) != null;
29
/// Parses the specified value.
31
/// <param name="value">The value.</param>
32
/// <returns></returns>
33
public T DeserializeFromString(string value)
35
if (string.IsNullOrEmpty(value)) return default(T);
36
return (T)JsonReader<T>.Parse(value);
39
public T DeserializeFromReader(TextReader reader)
41
return DeserializeFromString(reader.ReadToEnd());
44
public string SerializeToString(T value)
46
if (value == null) return null;
47
if (typeof(T) == typeof(string)) return value as string;
48
if (typeof(T) == typeof(object) || typeof(T).IsAbstract || typeof(T).IsInterface)
50
if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true;
51
var result = JsonSerializer.SerializeToString(value, value.GetType());
52
if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false;
56
var sb = new StringBuilder();
57
using (var writer = new StringWriter(sb))
59
JsonWriter<T>.WriteObject(writer, value);
64
public void SerializeToWriter(T value, TextWriter writer)
66
if (value == null) return;
67
if (typeof(T) == typeof(string))
72
if (typeof(T) == typeof(object) || typeof(T).IsAbstract || typeof(T).IsInterface)
74
if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true;
75
JsonSerializer.SerializeToWriter(value, value.GetType(), writer);
76
if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false;
80
JsonWriter<T>.WriteObject(writer, value);
b'\\ No newline at end of file'