Json.NET Deserialization into dynamic object with referencing

前端 未结 2 677
逝去的感伤
逝去的感伤 2020-12-21 01:31

How can I get Json.NET to deserialize into dynamic objects but still do reference resolution?
dynamic d=JsonConvert.DeserializeObject(...)

2条回答
  •  猫巷女王i
    2020-12-21 02:13

    The way I did it now is with a postprocessing step and a recursive function that's doing its own reference saving and rewiring:

        private static void Reffing(this IDictionary current, Action exchange,IDictionary refdic)
        {
            object value;
            if(current.TryGetValue("$ref", out value))
            {
                if(!refdic.TryGetValue((string) value, out value))
                    throw new Exception("ref not found ");
                if (exchange != null)
                    exchange(value);
                return;
            }
            if (current.TryGetValue("$id", out value))
            {
                refdic[(string) value] = current;
            }
            foreach (var kvp in current.ToList())
            {
                if (kvp.Key.StartsWith("$"))
                    continue;
                var expandoObject = kvp.Value as ExpandoObject;
                if(expandoObject != null)
                    Reffing(expandoObject,o => current[kvp.Key]=o,refdic);
                var list = kvp.Value as IList;
                if (list == null) continue;
                for (var i = 0; i < list.Count; i++)
                {
                    var lEO = list[i] as ExpandoObject;
                    if(lEO!=null)
                        Reffing(lEO,o => list[i]=o,refdic);
                }
            }
        }
    
    
    

    used as:

            var test = JsonConvert.DeserializeObject(...);
            var dictionary = new Dictionary();
            Reffing(test,null,dictionary);
    

    提交回复
    热议问题