using Lskj.Push.Push.Mode;
using Lskj.Push.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lskj.Push.Common
{
public class PlatformConverter:JsonConverter
{
///
/// Platform whether this instance can convert the specified object type.
///
/// Type of the object.
///
/// true if this instance can convert the specified object type; otherwise, false.
///
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(Platform))
return true;
return false;
}
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Platform platform = value as Platform;
if (platform == null)
{
return;
}
platform.Check();
if (platform.isAll())
{
writer.WriteValue(platform.allPlatform);
}
else
{
writer.WriteStartArray();
foreach (var item in platform.deviceTypes)
{
writer.WriteValue(item);
}
writer.WriteEndArray();
}
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing property value of the JSON that is being converted.
/// The calling serializer.
/// The object value.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Platform platform = Platform.all();
if (reader.TokenType == JsonToken.Null)
{
return null;
}
else if(reader.TokenType==JsonToken.StartArray)
{
platform.allPlatform = null;
platform.deviceTypes = ReadArray(reader);
}
else if (reader.TokenType==JsonToken.String)
{
platform.allPlatform = reader.Value.ToString();
}
else
{
return null;
}
return platform;
}
private HashSet ReadArray(JsonReader reader)
{
HashSet list = new HashSet();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.String:
list.Add(Convert.ToString(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
return list;
case JsonToken.Comment:
// skip
break;
default:
return null;
}
}
return null;
}
}
}