// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD // license as described in the file LICENSE. // // -------------------------------------------------------------------------------------------------------------------- using Newtonsoft.Json; using System; using System.Collections.Generic; namespace VW.Serializer { /// /// Custom JSON converter returning the underlying raw json (avoiding object allocation). /// public class JsonRawStringListConverter : JsonConverter, IVowpalWabbitJsonConverter { /// /// Supports string only. /// public override bool CanConvert(Type objectType) { return objectType == typeof(List); } /// /// Not implemented. /// public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } /// /// Outputs the string contents as JSON. /// public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var valueStringEnumerable = value as List; if (valueStringEnumerable != null) { writer.WriteStartArray(); foreach (var str in valueStringEnumerable) writer.WriteRawValue(str); writer.WriteEndArray(); return; } serializer.Serialize(writer, value); } /// /// List of independently parseable JSON fragments. /// public IEnumerable JsonFragments(object value) { var valueStringList = value as List; if (valueStringList == null) throw new ArgumentException($"Unsupported type: {value}"); return valueStringList; } } }