Created
July 28, 2015 02:15
-
-
Save programmation/2ab08608e0f4a1153f25 to your computer and use it in GitHub Desktop.
Json type converter used as attribute on convertible class
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
using Xamarin.Forms; | |
namespace App | |
{ | |
public class ConcreteTypeConverter<T> | |
: JsonConverter | |
{ | |
public override bool CanConvert (Type objectType) | |
{ | |
return true; | |
} | |
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
if (objectType == typeof(Xamarin.Forms.Color)) | |
{ | |
var colorString = (string)reader.Value; | |
if (colorString.StartsWith ("#")) | |
{ | |
if (colorString.Contains(";")) | |
{ | |
var colors = colorString.Split(new char[] { ';' }); | |
if (Device.OS == TargetPlatform.iOS) | |
{ | |
return Xamarin.Forms.Color.FromHex(colors[0]); | |
} | |
if (Device.OS == TargetPlatform.Android) | |
{ | |
return Xamarin.Forms.Color.FromHex(colors[1]); | |
} | |
} | |
return Xamarin.Forms.Color.FromHex (colorString); | |
} | |
} | |
if (objectType == typeof(List<INativeMenuItem>)) | |
{ | |
var list = serializer.Deserialize<List<NativeMenuItem>>(reader); | |
var ret = new List<INativeMenuItem> (); | |
foreach (var item in list) | |
{ | |
ret.Add (new NativeMenuItem { | |
Title = item.Title, | |
Url = item.Url, | |
}); | |
} | |
return ret; | |
} | |
return serializer.Deserialize<T> (reader); | |
} | |
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
serializer.Serialize (writer, value); | |
} | |
} | |
} | |
// Usage in StyleService.cs: | |
/* | |
[JsonConverter(typeof(ConcreteTypeConverter<Xamarin.Forms.Color>))] | |
public Color HeaderBarBackgroundColor { get; set; } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment