// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespace Microsoft.Graph
{
using System.IO;
using System.Text;
using Newtonsoft.Json;
///
/// An implementation using the JSON.NET serializer.
///
public class Serializer : ISerializer
{
JsonSerializerSettings jsonSerializerSettings;
///
/// Constructor for the serializer with defaults for the JsonSerializer settings.
///
public Serializer()
: this(
new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
TypeNameHandling = TypeNameHandling.None,
DateParseHandling = DateParseHandling.None
})
{
}
///
/// Constructor for the serializer.
///
/// The serializer settings to apply to the serializer.
public Serializer(JsonSerializerSettings jsonSerializerSettings)
{
this.jsonSerializerSettings = jsonSerializerSettings;
}
///
/// Deserializes the stream to an object of the specified type.
///
/// The deserialization type.
/// The stream to deserialize.
/// The deserialized object.
public T DeserializeObject(Stream stream)
{
if (stream == null)
{
return default(T);
}
using (var streamReader = new StreamReader(
stream,
Encoding.UTF8 /* encoding */,
true /* detectEncodingFromByteOrderMarks */,
4096 /* bufferSize */,
true /* leaveOpen */))
using (var textReader = new JsonTextReader(streamReader))
{
var jsonSerializer = JsonSerializer.Create(this.jsonSerializerSettings);
return jsonSerializer.Deserialize(textReader);
}
}
///
/// Deserializes the JSON string to an object of the specified type.
///
/// The deserialization type.
/// The JSON string to deserialize.
/// The deserialized object.
public T DeserializeObject(string inputString)
{
if (string.IsNullOrEmpty(inputString))
{
return default(T);
}
return JsonConvert.DeserializeObject(inputString, this.jsonSerializerSettings);
}
///
/// Serializes the specified object into a JSON string.
///
/// The object to serialize.
/// The JSON string.
public string SerializeObject(object serializeableObject)
{
if (serializeableObject == null)
{
return null;
}
var stream = serializeableObject as Stream;
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
var stringValue = serializeableObject as string;
if (stringValue != null)
{
return stringValue;
}
return JsonConvert.SerializeObject(serializeableObject, this.jsonSerializerSettings);
}
}
}