using Lskj.Push.Push.Mode; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lskj.Push.Common { public class AudienceConverter : 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(Audience)) 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) { Audience audience = value as Audience; if (audience == null) { return; } audience.Check(); if (audience.isAll()) { writer.WriteValue(audience.allAudience); //writer.WriteValue("alll"); } else { var json = JsonConvert.SerializeObject(audience.dictionary); writer.WriteRawValue(json); } } /// /// 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) { Audience audience = Audience.all(); if (reader.TokenType == JsonToken.Null) { return null; } else if (reader.TokenType == JsonToken.String) { audience.allAudience = reader.Value.ToString(); } else if (reader.TokenType == JsonToken.StartObject) { audience.allAudience = null; Dictionary> dictionary=new Dictionary>(); string key="key"; HashSet value=null; while (reader.Read()) { Debug.WriteLine("Type:{0},Path:{1}", reader.TokenType, reader.Path); switch (reader.TokenType) { case JsonToken.StartObject: break; case JsonToken.PropertyName: key = reader.Value.ToString(); break; case JsonToken.StartArray: value = new HashSet(); break; case JsonToken.String: value.Add(reader.Value.ToString()); break; case JsonToken.EndArray: { dictionary.Add(key,value); } break; case JsonToken.EndObject: return audience; } } audience.dictionary = dictionary; } return audience; } } }