Skip to content

Instantly share code, notes, and snippets.

@wayne-o
Created March 17, 2012 20:06
Show Gist options
  • Save wayne-o/2064848 to your computer and use it in GitHub Desktop.
Save wayne-o/2064848 to your computer and use it in GitHub Desktop.
NodaOffsetConverter
using Newtonsoft.Json;
using NodaTime.ZoneInfoCompiler;
namespace NodaTime.Serialization.JsonNet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// TODO: Update summary.
/// </summary>
public class NodaOffsetConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!(value is Offset))
throw new Exception(string.Format("Unexpected value when converting. Expected NodaTime.Offset, got {0}.", value.GetType().FullName));
var offset = (Offset)value;
var text = offset.TotalTicks;
writer.WriteValue(text);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (objectType != typeof(Offset?))
throw new Exception(string.Format("Cannot convert null value to {0}.", objectType));
return null;
}
if (reader.TokenType != JsonToken.Integer)
throw new Exception(string.Format("Unexpected token parsing instant. Expected Integer, got {0}.", reader.TokenType));
var offsetStrng = reader.Value.ToString();
long offset;
try
{
long.TryParse(offsetStrng, out offset);
}
catch (Exception e)
{
// TODO: is this right?
// Log.Error("Exception {0} occurred: {1}", e.GetType().Name, e.StackTrace);
throw;
}
if (objectType == typeof(Offset?))
return null;
return Offset.FromTicks(offset);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Offset) || objectType == typeof(Offset?);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment