Created
May 22, 2015 09:12
-
-
Save softlion/680e54cf6b30504790ca to your computer and use it in GitHub Desktop.
Implementation of an IMvxTextSerializer that can be put inside a PCL and uses the latest version of Newtonsoft.Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class MvxJsonTextSerializer : IMvxJsonConverter | |
{ | |
private static readonly JsonSerializerSettings Settings; | |
public static void Register() | |
{ | |
Mvx.RegisterType<IMvxJsonConverter, MvxJsonTextSerializer>(); | |
Mvx.RegisterType<IMvxTextSerializer, MvxJsonTextSerializer>(); | |
} | |
static MvxJsonTextSerializer() | |
{ | |
Settings = new JsonSerializerSettings | |
{ | |
ReferenceLoopHandling = ReferenceLoopHandling.Serialize, | |
Converters = new List<JsonConverter> | |
{ | |
new MvxEnumJsonConverter(), | |
}, | |
DateFormatHandling = DateFormatHandling.IsoDateFormat, | |
}; | |
} | |
public object DeserializeObject(Type type, string inputText) | |
{ | |
return JsonConvert.DeserializeObject(inputText, type, Settings); | |
} | |
public T DeserializeObject<T>(string inputText) | |
{ | |
return JsonConvert.DeserializeObject<T>(inputText, Settings); | |
} | |
public string SerializeObject(object toSerialise) | |
{ | |
return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings); | |
} | |
} | |
public class MvxEnumJsonConverter : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
return objectType.GetTypeInfo().IsEnum; | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
writer.WriteValue(value.ToString()); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
var theString = reader.Value.ToString(); | |
return Enum.Parse(objectType, theString, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment