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)
180 public MethodInfo OnDeserializing { get; set; }
181 public MethodInfo OnDeserialized { get; set; }
183 public virtual void Serialize (JsonSerializationWriter outputter, object graph, string type)
185 outputter.Writer.WriteAttributeString ("type", type);
186 foreach (TypeMapMember member in members) {
187 object memberObj = member.GetMemberOf (graph);
188 // FIXME: consider EmitDefaultValue
189 outputter.Writer.WriteStartElement (member.Name);
190 outputter.WriteObjectContent (memberObj, false, false);
191 outputter.Writer.WriteEndElement ();
195 internal static object CreateInstance (Type type)
197 if (TypeMap.IsDictionary (type)) {
198 if (type.IsGenericType)
199 return Activator.CreateInstance (typeof (Dictionary<,>).MakeGenericType (type.GetGenericArguments ()));
201 return new Hashtable ();
202 } else if (TypeMap.IsCollection (type)) {
203 if (type.IsGenericType)
204 return Activator.CreateInstance (typeof (List<>).MakeGenericType (type.GetGenericArguments ()));
206 return new ArrayList ();
209 return FormatterServices.GetUninitializedObject (type);
212 public virtual object Deserialize (JsonSerializationReader jsr)
214 XmlReader reader = jsr.Reader;
215 bool isNull = reader.GetAttribute ("type") == "null";
217 object ret = isNull ? null : CreateInstance (type);
218 if (ret != null && OnDeserializing != null)
219 OnDeserializing.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
220 Dictionary<TypeMapMember,bool> filled = new Dictionary<TypeMapMember,bool> ();
222 reader.ReadStartElement ();
223 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
224 bool consumed = false;
225 for (int i = 0; i < members.Length; i++) {
226 TypeMapMember mm = members [i];
227 if (mm.Name == reader.LocalName && reader.NamespaceURI == String.Empty) {
228 if (filled.ContainsKey (mm))
229 throw new SerializationException (String.Format ("Object content '{0}' for '{1}' already appeared in the reader", reader.LocalName, type));
230 mm.SetMemberValue (ret, jsr.ReadObject (mm.Type));
239 reader.ReadEndElement ();
240 if (ret != null && OnDeserialized != null)
241 OnDeserialized.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
246 abstract class TypeMapMember
249 DataMemberAttribute dma;
251 protected TypeMapMember (MemberInfo mi, DataMemberAttribute dma)
258 get { return dma == null ? mi.Name : dma.Name ?? mi.Name; }
261 public bool EmitDefaultValue {
262 get { return dma != null && dma.EmitDefaultValue; }
265 public bool IsRequired {
266 get { return dma != null && dma.IsRequired; }
270 get { return dma != null ? dma.Order : -1; }
273 public abstract Type Type { get; }
275 public abstract object GetMemberOf (object owner);
277 public abstract void SetMemberValue (object owner, object value);
280 class TypeMapField : TypeMapMember
284 public TypeMapField (FieldInfo fi, DataMemberAttribute dma)
290 public override Type Type {
291 get { return field.FieldType; }
294 public override object GetMemberOf (object owner)
296 return field.GetValue (owner);
299 public override void SetMemberValue (object owner, object value)
301 field.SetValue (owner, value);
305 class TypeMapProperty : TypeMapMember
307 PropertyInfo property;
309 public TypeMapProperty (PropertyInfo pi, DataMemberAttribute dma)
315 public override Type Type {
316 get { return property.PropertyType; }
319 public override object GetMemberOf (object owner)
321 return property.GetValue (owner, null);
324 public override void SetMemberValue (object owner, object value)
326 property.SetValue (owner, value, null);