Beispiel #1
0
        static object Deserialize(JsonObject obj, Type t)
        {
            if (t.IsGenericType)
            {
                Type        btype  = t.GetGenericTypeDefinition();
                Type[]      gtypes = t.GetGenericArguments();
                IDictionary dic    = (IDictionary)t.GetConstructor(Type.EmptyTypes).Invoke(null);
                if (btype == JsonSerializer.DictionaryType && gtypes[0] == typeof(string))
                {
                    foreach (KeyValuePair <string, JsonValue> pair in obj.Value)
                    {
                        dic.Add(pair.Key, Deserialize(pair.Value, gtypes[1]));
                    }
                }
                return(dic);
            }

            SerializationCache c = SerializationCache.Get(t);
            object             r = FormatterServices.GetUninitializedObject(t);

            for (int i = 0; i < c.Attributes.Length; i++)
            {
                JsonValue v;
                JsonObjectMappingAttribute att = c.Attributes[i];
                PropertyInfo prop = c.Properties[i];
                if (!obj.Value.TryGetValue(att.Key, out v) || v.ValueType != att.ValueType)
                {
                    continue;
                }
                prop.SetValue(r, Deserialize(v, prop.PropertyType), null);
            }
            return(r);
        }
Beispiel #2
0
        static void Serialize(JsonTextWriter writer, object obj)
        {
            writer.WriteStartObject();

            Type type    = obj.GetType();
            bool handled = false;

            if (type.IsGenericType)
            {
                Type   btype  = type.GetGenericTypeDefinition();
                Type[] gtypes = type.GetGenericArguments();
                if (btype == DictionaryType && gtypes[0] == typeof(string))
                {
                    IDictionary   dic   = obj as IDictionary;
                    JsonValueType vtype = GetJsonValueType(gtypes[1]);
                    foreach (object key in dic.Keys)
                    {
                        writer.WriteKey((string)key);
                        Serialize(writer, vtype, dic[key]);
                    }
                    handled = true;
                }
            }

            if (!handled)
            {
                SerializationCache c = SerializationCache.Get(type);
                for (int i = 0; i < c.Attributes.Length; i++)
                {
                    PropertyInfo p = c.Properties[i];
                    JsonObjectMappingAttribute a = c.Attributes[i];

                    object v = p.GetValue(obj, null);
                    if (v == null)
                    {
                        continue;
                    }
                    writer.WriteKey(a.Key);
                    Serialize(writer, a.ValueType, v);
                }
            }

            writer.WriteEndObject();
        }