2010-01-20 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mcs / class / System.ServiceModel.Web / System.Runtime.Serialization.Json / JsonSerializationReader.cs
1 //
2 // JsonSerializationReader.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28 using System;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Collections.ObjectModel;
32 using System.Globalization;
33 using System.IO;
34 using System.Reflection;
35 using System.Text;
36 using System.Xml;
37
38 namespace System.Runtime.Serialization.Json
39 {
40         class JsonSerializationReader
41         {
42                 DataContractJsonSerializer serializer;
43                 XmlReader reader;
44                 int serialized_object_count;
45                 bool verify_object_name;
46                 Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
47                 Type root_type;
48
49                 public JsonSerializationReader (DataContractJsonSerializer serializer, XmlReader reader, Type rootType, bool verifyObjectName)
50                 {
51                         this.serializer = serializer;
52                         this.reader = reader;
53                         this.root_type = rootType;
54                         this.verify_object_name = verifyObjectName;
55                 }
56
57                 public XmlReader Reader {
58                         get { return reader; }
59                 }
60
61                 public object ReadRoot ()
62                 {
63                         TypeMap rootMap = GetTypeMap (root_type);
64
65                         object v = ReadObject (root_type);
66                         return v;
67                 }
68
69                 public object ReadObject (Type type)
70                 {
71                         if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
72                                 throw SerializationError (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
73
74                         switch (Type.GetTypeCode (type)) {
75                         case TypeCode.DBNull:
76                                 string dbn = reader.ReadElementContentAsString ();
77                                 if (dbn != String.Empty)
78                                         throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
79                                 return DBNull.Value;
80                         case TypeCode.String:
81                                 return reader.ReadElementContentAsString ();
82                         case TypeCode.Single:
83                                 return reader.ReadElementContentAsFloat ();
84                         case TypeCode.Double:
85                                 return reader.ReadElementContentAsDouble ();
86                         case TypeCode.Decimal:
87                                 return reader.ReadElementContentAsDecimal ();
88                         case TypeCode.Byte:
89                         case TypeCode.SByte:
90                         case TypeCode.Int16:
91                         case TypeCode.Int32:
92                         case TypeCode.UInt16:
93                         case TypeCode.UInt32:
94                                 int i = reader.ReadElementContentAsInt ();
95                                 if (type.IsEnum)
96                                         return Enum.ToObject (type, (object)i);
97                                 else
98                                         return Convert.ChangeType (i, type, null);
99                         case TypeCode.Int64:
100                         case TypeCode.UInt64:
101                                 long l = reader.ReadElementContentAsLong ();
102                                 if (type.IsEnum)
103                                         return Enum.ToObject (type, (object)l);
104                                 else
105                                         return Convert.ChangeType (l, type, null);
106                         case TypeCode.Boolean:
107                                 return reader.ReadElementContentAsBoolean ();
108                         default:
109                                 if (type == typeof (Guid)) {
110                                         return new Guid (reader.ReadElementContentAsString ());
111                                 } else if (type == typeof (Uri)) {
112                                         return new Uri (reader.ReadElementContentAsString ());
113                                 } else if (type == typeof (XmlQualifiedName)) {
114                                         string s = reader.ReadElementContentAsString ();
115                                         int idx = s.IndexOf (':');
116                                         return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
117                                 } else if (type != typeof (object)) {
118                                         // strongly-typed object
119                                         if (reader.IsEmptyElement) {
120                                                 // empty -> null array or object
121                                                 reader.Read ();
122                                                 return null;
123                                         }
124
125                                         Type ct = GetCollectionType (type);
126                                         if (ct != null) {
127                                                 return DeserializeGenericCollection (type, ct);
128                                         } else {
129                                                 TypeMap map = GetTypeMap (type);
130                                                 return map.Deserialize (this);
131                                         }
132                                 }
133                                 else
134                                         return ReadInstanceDrivenObject ();
135                         }
136                 }
137
138                 Type GetRuntimeType (string name)
139                 {
140                         name = ToRuntimeTypeName (name);
141                         if (serializer.KnownTypes != null)
142                                 foreach (Type t in serializer.KnownTypes)
143                                         if (t.FullName == name)
144                                                 return t;
145                         var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
146                         if (ret != null)
147                                 return ret;
148 #if !NET_2_1 // how to do that in ML?
149                         // We probably have to iterate all the existing
150                         // assemblies that are loaded in current domain.
151                         foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
152                                 ret = ass.GetType (name, false);
153                                 if (ret != null)
154                                         return ret;
155                         }
156 #endif
157                         return null;
158                 }
159
160                 object ReadInstanceDrivenObject ()
161                 {
162                         string type = reader.GetAttribute ("type");
163                         if (type == "object") {
164                                 string runtimeType = reader.GetAttribute ("__type");
165                                 if (runtimeType != null) {
166                                         Type t = GetRuntimeType (runtimeType);
167                                         if (t == null)
168                                                 throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
169                                         return ReadObject (t);
170                                 }
171                         }
172                         string v = reader.ReadElementContentAsString ();
173                         switch (type) {
174                         case "boolean":
175                                 switch (v) {
176                                 case "true":
177                                         return true;
178                                 case "false":
179                                         return false;
180                                 default:
181                                         throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
182                                 }
183                         case "string":
184                                 return v;
185                         case "null":
186                                 if (v != "null")
187                                         throw SerializationError (String.Format ("Invalid JSON null value: {0}", v));
188                                 return null;
189                         case "number":
190                                 int i;
191                                 if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
192                                         return i;
193                                 long l;
194                                 if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
195                                         return l;
196                                 ulong ul;
197                                 if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
198                                         return ul;
199                                 double dbl;
200                                 if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
201                                         return dbl;
202                                 decimal dec;
203                                 if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
204                                         return dec;
205                                 throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
206                         default:
207                                 throw SerializationError (String.Format ("Unexpected type: {0}", type));
208                         }
209                 }
210
211                 string FormatTypeName (Type type)
212                 {
213                         return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
214                 }
215
216                 string ToRuntimeTypeName (string s)
217                 {
218                         int idx = s.IndexOf (":#", StringComparison.Ordinal);
219                         return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
220                 }
221
222                 Type GetCollectionType (Type type)
223                 {
224                         if (type.IsArray)
225                                 return type.GetElementType ();
226                         if (type.IsGenericType) {
227                                 // returns T for ICollection<T>
228                                 Type [] ifaces = type.GetInterfaces ();
229                                 foreach (Type i in ifaces)
230                                         if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (ICollection<>)))
231                                                 return i.GetGenericArguments () [0];
232                         }
233                         if (typeof (IList).IsAssignableFrom (type))
234                                 // return typeof(object) for mere collection.
235                                 return typeof (object);
236                         else
237                                 return null;
238                 }
239
240                 object DeserializeGenericCollection (Type collectionType, Type elementType)
241                 {
242                         reader.ReadStartElement ();
243                         object ret;
244                         if (typeof (IList).IsAssignableFrom (collectionType)) {
245 #if NET_2_1
246                                 Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
247 #else
248                                 Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
249 #endif
250                                 IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
251                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
252                                         if (!reader.IsStartElement ("item"))
253                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
254                                         Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
255                                         object elem = ReadObject (et ?? typeof (object));
256                                         c.Add (elem);
257                                 }
258 #if NET_2_1
259                                 if (collectionType.IsArray) {
260                                         Array array = Array.CreateInstance (elementType, c.Count);
261                                         c.CopyTo (array, 0);
262                                         ret = array;
263                                 }
264                                 else
265                                         ret = c;
266 #else
267                                 ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
268 #endif
269                         } else {
270                                 object c = Activator.CreateInstance (collectionType);
271                                 MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
272                                 if (add == null) {
273                                         var icoll = typeof (ICollection<>).MakeGenericType (elementType);
274                                         if (icoll.IsAssignableFrom (c.GetType ()))
275                                                 add = icoll.GetMethod ("Add");
276                                 }
277                                 
278                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
279                                         if (!reader.IsStartElement ("item"))
280                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
281                                         object elem = ReadObject (elementType);
282                                         add.Invoke (c, new object [] {elem});
283                                 }
284                                 ret = c;
285                         }
286
287                         reader.ReadEndElement ();
288                         return ret;
289                 }
290
291                 TypeMap GetTypeMap (Type type)
292                 {
293                         TypeMap map;
294                         if (!typemaps.TryGetValue (type, out map)) {
295                                 map = TypeMap.CreateTypeMap (type);
296                                 typemaps [type] = map;
297                         }
298                         return map;
299                 }
300
301                 Exception SerializationError (string basemsg)
302                 {
303                         IXmlLineInfo li = reader as IXmlLineInfo;
304                         if (li == null || !li.HasLineInfo ())
305                                 return new SerializationException (basemsg);
306                         else
307                                 return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
308                 }
309         }
310 }