Exemple #1
0
 /// <summary>
 /// 尝试给当前对象用json数据赋值
 /// </summary>
 /// <param name="data"></param>
 /// <param name="json"></param>
 /// <returns>如果是struct需要用返回值覆盖,class不需要</returns>
 public static IJsonData Pause(this IJsonData data, string json)
 {
     if (!string.IsNullOrEmpty(json))
     {
         JsonUtility.FromJsonOverwrite(json, data);
     }
     return(data);
 }
Exemple #2
0
 /// <summary>
 /// Performs a deferred deserialization to obtain a new wrapped object corresponding to the
 /// contents of the stored JSON data. The actual deserialization is delegated to the base
 /// prototype of the class hierarchy. This prototype is then responsible to find an
 /// appropriate class in the hierarchy and map the JSON data to an instance of the class.
 /// </summary>
 ///
 public void Deserialize()
 {
     Atomic(() => Object == null && jsonData != null, () =>
     {
         Object = Prototyped <TBase> .BasePrototype.Deserialize(jsonData);
         jsonData.Dispose();
         jsonData = null;
     });
 }
        public IndexModule(IJsonData provider)
        {
            Get["/"] = p =>
            {
                var getTask = provider.GetAllVehicles();
                var bytes = Encoding.UTF8.GetBytes(getTask.Result);

                var response = new Response()
                {
                    ContentType = "application/json",
                    Contents = s => s.Write(bytes, 0, bytes.Length)
                };

                return response;
            };
        }
Exemple #4
0
        public object Deserialize(IJsonData jsonData)
        {
            var data = jsonData as JsonData;

            if (data == null)
            {
                return(null);
            }

            if (data.XmlStream == null && !Parse(data))
            {
                return(null);
            }

            lock (CriticalSection) {
                try {
                    using (reader = XmlReader.Create(data.XmlStream)) {
                        var obj = serializer.ReadObject(reader, false);

                        var container = obj as IDeferredObjectContainer;
                        if (container != null)
                        {
                            deferredObjects.ForEach(x => container.Add(x));
                        }

                        return(obj);
                    }
                } catch (Exception e) {
                    System.Diagnostics.Debug.WriteLine(
                        e.Message + "\r\n\r\nStacktrace:\r\n" + e.StackTrace);
                    return(null);
                } finally {
                    reader = null;
                    deferredObjects.Clear();
                    data.XmlStream.Position = 0;
                }
            }
        }
Exemple #5
0
 [OnDeserializing] // <-- Invoked by serializer before deserializing this object
 void OnDeserializing(StreamingContext context)
 {
     // Store JSON data corresponding to this object
     jsonData = Serializer.GetCurrentJsonData();
 }
Exemple #6
0
        /// <summary>
        /// Traverse this class hierarchy looking for the most suitable derived class that can be
        /// used as target type for the deserialization of the JSON data provided.
        /// </summary>
        /// <param name="initArgs">Additional arguments required for object initialization</param>
        /// <param name="jsonData">Parsed JSON data</param>
        /// <returns>Deserialized object, or null if deserialization failed</returns>
        ///
        protected static TBase DeserializeClassHierarchy(object initArgs, IJsonData jsonData)
        {
            //  PSEUDOCODE:
            //
            //  Nodes to visit := base of class hierarchy.
            //  While there are still nodes to visit
            //      Current node ::= Extract next node to visit.
            //      Tentative object := Deserialize using current node as target type.
            //      If deserialization failed
            //          Skip branch, continue (with next node, if any).
            //      Else
            //          Test compatibility of current node with tentative object.
            //          If not compatible
            //              Skip branch, continue (with next node, if any).
            //          If compatible
            //              If leaf node
            //                  Found suitable node!!
            //                  Return tentative object as final result of deserialization.
            //              Else
            //                  Save tentative object as last sucessful deserialization.
            //                  Add child nodes to the nodes to visit.
            //          If inconclusive (i.e. a child node might be compatible)
            //              Add child nodes to the nodes to visit.
            //  If no suitable node was found
            //      Return last sucessful deserialization as final result of deserialization.

            lock (BaseClass.Prototype.CriticalSection) {
                var   toDo = new Queue <SubClass>(new[] { BaseClass });
                TBase lastCompatibleObj = null;

                // Traverse class hierarchy tree looking for a compatible leaf node
                // i.e. compatible class without any sub-classes
                while (toDo.Count > 0)
                {
                    var subClass = toDo.Dequeue();

                    // Try to deserialize as sub-class
                    TBase tryObj;
                    if (jsonData.IsEmpty())
                    {
                        tryObj = CreateInstance(subClass.Type);
                    }
                    else
                    {
                        tryObj = subClass.Prototype.Serializer.Deserialize(jsonData) as TBase;
                    }

                    if (tryObj == null)
                    {
                        continue; // Not deserializable as this type
                    }
                    tryObj.InitializeObject(initArgs);

                    // Test compatbility
                    var isCompatible = subClass.Prototype.IsCompatible(tryObj);

                    if (isCompatible == false)
                    {
                        // Incompatible
                        continue;
                    }
                    else if (isCompatible == true)
                    {
                        // Compatible

                        if (!subClass.SubTypes.Any())
                        {
                            return(tryObj); // Found compatible leaf node!
                        }
                        // Non-leaf node; continue searching
                        lastCompatibleObj = tryObj;
                        PotentialSubClasses(subClass, tryObj)
                        .ForEach(x => toDo.Enqueue(x));
                        continue;
                    }
                    else
                    {
                        // Maybe has compatible derived class

                        if (subClass.SubTypes.Any())
                        {
                            // Non-leaf node; continue searching
                            PotentialSubClasses(subClass, tryObj)
                            .ForEach(x => toDo.Enqueue(x));
                        }
                        continue;
                    }
                }

                // No compatible leaf node found
                // Use last successful (non-leaf) deserializtion, if any
                return(lastCompatibleObj);
            }
        }
Exemple #7
0
        /// <summary>
        /// Perform a deferred deserialization based on this class hierarchy.
        /// </summary>
        /// <param name="jsonData">Data to deserialize</param>
        /// <returns>Deserialized object</returns>
        ///
        TBase IDeferrable <TBase> .Deserialize(IJsonData jsonData)
        {
            System.Diagnostics.Debug.Assert(this == BasePrototype);

            return(DeserializeClassHierarchy(null, jsonData));
        }
Exemple #8
0
 /// <summary>
 /// 创建并返回一个copy
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="data"></param>
 /// <returns></returns>
 public static T Copy <T>(this IJsonData data) where T : IJsonData
 {
     return(JsonUtility.FromJson <T>(data.ToJson()));
 }
Exemple #9
0
 /// <summary>
 /// 转换成json
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static string ToJson(this IJsonData data)
 {
     return(data == null ? null : JsonUtility.ToJson(data));
 }
Exemple #10
0
 public static JsonData WriteJsonData(this JsonData jd, string key, IJsonData value)
 {
     jd[key] = value.ToJsonData();
     return(jd);
 }
Exemple #11
0
 public JsonResponse(IJsonData data, HttpStatusCode statusCode)
 {
     this.Data       = data;
     this.StatusCode = statusCode;
 }