5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Collections.ObjectModel;
32 using System.Globalization;
35 using System.Reflection;
36 using System.Runtime.Serialization;
40 namespace System.Runtime.Serialization.Json
44 static bool IsInvalidNCName (string name)
46 if (name == null || name.Length == 0)
49 XmlConvert.VerifyNCName (name);
50 } catch (XmlException) {
56 public static TypeMap CreateTypeMap (Type type)
58 object [] atts = type.GetCustomAttributes (typeof (DataContractAttribute), true);
60 return CreateTypeMap (type, (DataContractAttribute) atts [0]);
62 atts = type.GetCustomAttributes (typeof (SerializableAttribute), false);
64 return CreateTypeMap (type, null);
66 if (IsPrimitiveType (type))
70 if (ExternalTypeMap.HasType (type))
71 return new ExternalTypeMap (type);
73 return CreateDefaultTypeMap (type);
76 static bool IsPrimitiveType (Type type)
80 if (Type.GetTypeCode (type) != TypeCode.Object)
81 return true; // FIXME: it is likely hacky
85 static TypeMap CreateDefaultTypeMap (Type type)
87 var l = new List<TypeMapMember> ();
88 foreach (var fi in type.GetFields ())
90 l.Add (new TypeMapField (fi, null));
91 foreach (var pi in type.GetProperties ())
92 if (pi.CanRead && pi.CanWrite && !pi.GetGetMethod ().IsStatic && pi.GetIndexParameters ().Length == 0)
93 l.Add (new TypeMapProperty (pi, null));
94 l.Sort ((x, y) => x.Order != y.Order ? x.Order - y.Order : String.Compare (x.Name, y.Name, StringComparison.Ordinal));
95 return new TypeMap (type, null, l.ToArray ());
98 internal static bool IsDictionary (Type type)
100 if (type.GetInterface ("System.Collections.IDictionary", false) != null)
102 if (type.GetInterface ("System.Collections.Generic.IDictionary`2", false) != null)
107 internal static bool IsCollection (Type type)
109 if (IsPrimitiveType (type) || IsDictionary (type))
111 if (type.GetInterface ("System.Collections.IEnumerable", false) != null)
116 static TypeMap CreateTypeMap (Type type, DataContractAttribute dca)
118 if (dca != null && dca.Name != null && IsInvalidNCName (dca.Name))
119 throw new InvalidDataContractException (String.Format ("DataContractAttribute for type '{0}' has an invalid name", type));
121 List<TypeMapMember> members = new List<TypeMapMember> ();
123 foreach (FieldInfo fi in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
125 object [] atts = fi.GetCustomAttributes (typeof (DataMemberAttribute), true);
126 if (atts.Length == 0)
128 DataMemberAttribute dma = (DataMemberAttribute) atts [0];
129 members.Add (new TypeMapField (fi, dma));
131 if (fi.GetCustomAttributes (typeof (IgnoreDataMemberAttribute), false).Length > 0)
133 members.Add (new TypeMapField (fi, null));
138 foreach (PropertyInfo pi in type.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
139 object [] atts = pi.GetCustomAttributes (typeof (DataMemberAttribute), true);
140 if (atts.Length == 0)
142 if (pi.GetIndexParameters ().Length > 0)
144 if (IsCollection (pi.PropertyType)) {
146 throw new InvalidDataContractException (String.Format ("Property {0} must have a getter", pi));
148 else if (!pi.CanRead || !pi.CanWrite)
149 throw new InvalidDataContractException (String.Format ("Non-collection property {0} must have both getter and setter", pi));
150 DataMemberAttribute dma = (DataMemberAttribute) atts [0];
151 members.Add (new TypeMapProperty (pi, dma));
155 members.Sort (delegate (TypeMapMember m1, TypeMapMember m2) { return m1.Order != m2.Order ? m1.Order - m2.Order : String.CompareOrdinal (m1.Name, m2.Name); });
156 return new TypeMap (type, dca == null ? null : dca.Name, members.ToArray ());
161 TypeMapMember [] members;
163 static readonly Type [] deser_methods_args = new Type [] { typeof (StreamingContext) };
164 const BindingFlags binding_flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
166 public TypeMap (Type type, string element, TypeMapMember [] orderedMembers)
169 this.element = element;
170 this.members = orderedMembers;
172 foreach (var mi in type.GetMethods (binding_flags)) {
173 if (mi.GetCustomAttributes (typeof (OnDeserializingAttribute), false).Length > 0)
174 OnDeserializing = mi;
175 else if (mi.GetCustomAttributes (typeof (OnDeserializedAttribute), false).Length > 0)
177 else if (mi.GetCustomAttributes (typeof (OnSerializingAttribute), false).Length > 0)
179 else if (mi.GetCustomAttributes (typeof (OnSerializedAttribute), false).Length > 0)
184 public MethodInfo OnDeserializing { get; set; }
185 public MethodInfo OnDeserialized { get; set; }
186 public MethodInfo OnSerializing { get; set; }
187 public MethodInfo OnSerialized { get; set; }
189 public virtual void Serialize (JsonSerializationWriter outputter, object graph, string type)
191 if (OnSerializing != null)
192 OnSerializing.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
194 outputter.Writer.WriteAttributeString ("type", type);
195 foreach (TypeMapMember member in members) {
196 object memberObj = member.GetMemberOf (graph);
197 // FIXME: consider EmitDefaultValue
198 outputter.Writer.WriteStartElement (member.Name);
199 outputter.WriteObjectContent (memberObj, false, false);
200 outputter.Writer.WriteEndElement ();
203 if (OnSerialized != null)
204 OnSerialized.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
207 internal static object CreateInstance (Type type)
209 if (TypeMap.IsDictionary (type)) {
210 if (type.IsGenericType)
211 return Activator.CreateInstance (typeof (Dictionary<,>).MakeGenericType (type.GetGenericArguments ()));
213 return new Hashtable ();
214 } else if (TypeMap.IsCollection (type)) {
215 if (type.IsGenericType)
216 return Activator.CreateInstance (typeof (List<>).MakeGenericType (type.GetGenericArguments ()));
218 return new ArrayList ();
221 return FormatterServices.GetUninitializedObject (type);
224 public virtual object Deserialize (JsonSerializationReader jsr)
226 XmlReader reader = jsr.Reader;
227 bool isNull = reader.GetAttribute ("type") == "null";
229 object ret = isNull ? null : CreateInstance (type);
230 if (ret != null && OnDeserializing != null)
231 OnDeserializing.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
232 Dictionary<TypeMapMember,bool> filled = new Dictionary<TypeMapMember,bool> ();
234 reader.ReadStartElement ();
235 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
236 bool consumed = false;
237 for (int i = 0; i < members.Length; i++) {
238 TypeMapMember mm = members [i];
239 if (mm.Name == reader.LocalName && reader.NamespaceURI == String.Empty) {
240 if (filled.ContainsKey (mm))
241 throw new SerializationException (String.Format ("Object content '{0}' for '{1}' already appeared in the reader", reader.LocalName, type));
242 mm.SetMemberValue (ret, jsr.ReadObject (mm.Type));
251 reader.ReadEndElement ();
252 if (ret != null && OnDeserialized != null)
253 OnDeserialized.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
258 abstract class TypeMapMember
261 DataMemberAttribute dma;
263 protected TypeMapMember (MemberInfo mi, DataMemberAttribute dma)
270 get { return dma == null ? mi.Name : dma.Name ?? mi.Name; }
273 public bool EmitDefaultValue {
274 get { return dma != null && dma.EmitDefaultValue; }
277 public bool IsRequired {
278 get { return dma != null && dma.IsRequired; }
282 get { return dma != null ? dma.Order : -1; }
285 public abstract Type Type { get; }
287 public abstract object GetMemberOf (object owner);
289 public abstract void SetMemberValue (object owner, object value);
292 class TypeMapField : TypeMapMember
296 public TypeMapField (FieldInfo fi, DataMemberAttribute dma)
302 public override Type Type {
303 get { return field.FieldType; }
306 public override object GetMemberOf (object owner)
308 return field.GetValue (owner);
311 public override void SetMemberValue (object owner, object value)
313 field.SetValue (owner, value);
317 class TypeMapProperty : TypeMapMember
319 PropertyInfo property;
321 public TypeMapProperty (PropertyInfo pi, DataMemberAttribute dma)
327 public override Type Type {
328 get { return property.PropertyType; }
331 public override object GetMemberOf (object owner)
333 return property.GetValue (owner, null);
336 public override void SetMemberValue (object owner, object value)
338 property.SetValue (owner, value, null);