using ln.json; using ln.json.mapping; using ln.objects.collections; using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace ln.objects.serialization.json { public class LazyListMapping : JSONMapping where T:class { ObjectStore ObjectStore; Type ElementType; public LazyListMapping(ObjectStore objectStore) :base(typeof(IList<>)) { ObjectStore = objectStore; ElementType = typeof(T); } public override JSONValue ToJson(JSONMapper mapper, object value) { if (!(value is IList ilist)) throw new ArgumentException(nameof(value)); JSONArray jsonArray = new JSONArray(); foreach (T item in ilist) if (mapper.Serialize(item, out JSONValue jsonItem)) jsonArray.Add(jsonItem); else throw new SerializationException(); return jsonArray; } public override object FromJson(JSONMapper mapper, JSONValue json) { IList ilist = new LazyList(ObjectStore); JSONArray jsonArray = json as JSONArray; foreach (JSONValue item in jsonArray.Children) ilist.Add((T)mapper.FromJson(item, ElementType)); return ilist; } } }