2010-01-27 Atsushi Enomoto <atsushi@ximian.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                         bool isNull = reader.GetAttribute ("type") == "null";
75
76                         switch (Type.GetTypeCode (type)) {
77                         case TypeCode.DBNull:
78                                 string dbn = reader.ReadElementContentAsString ();
79                                 if (dbn != String.Empty)
80                                         throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
81                                 return DBNull.Value;
82                         case TypeCode.String:
83                                 return isNull ? null : reader.ReadElementContentAsString ();
84                         case TypeCode.Single:
85                                 return reader.ReadElementContentAsFloat ();
86                         case TypeCode.Double:
87                                 return reader.ReadElementContentAsDouble ();
88                         case TypeCode.Decimal:
89                                 return reader.ReadElementContentAsDecimal ();
90                         case TypeCode.Byte:
91                         case TypeCode.SByte:
92                         case TypeCode.Int16:
93                         case TypeCode.Int32:
94                         case TypeCode.UInt16:
95                         case TypeCode.UInt32:
96                                 int i = reader.ReadElementContentAsInt ();
97                                 if (type.IsEnum)
98                                         return Enum.ToObject (type, (object)i);
99                                 else
100                                         return Convert.ChangeType (i, type, null);
101                         case TypeCode.Int64:
102                         case TypeCode.UInt64:
103                                 long l = reader.ReadElementContentAsLong ();
104                                 if (type.IsEnum)
105                                         return Enum.ToObject (type, (object)l);
106                                 else
107                                         return Convert.ChangeType (l, type, null);
108                         case TypeCode.Boolean:
109                                 return reader.ReadElementContentAsBoolean ();
110                         default:
111                                 if (type == typeof (Guid)) {
112                                         return new Guid (reader.ReadElementContentAsString ());
113                                 } else if (type == typeof (Uri)) {
114                                         return isNull ? null : new Uri (reader.ReadElementContentAsString ());
115                                 } else if (type == typeof (XmlQualifiedName)) {
116                                         string s = reader.ReadElementContentAsString ();
117                                         int idx = s.IndexOf (':');
118                                         return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
119                                 } else if (type != typeof (object)) {
120                                         // strongly-typed object
121                                         if (reader.IsEmptyElement) {
122                                                 // empty -> null array or object
123                                                 reader.Read ();
124                                                 return null;
125                                         }
126
127                                         Type ct = GetCollectionType (type);
128                                         if (ct != null) {
129                                                 return DeserializeGenericCollection (type, ct);
130                                         } else {
131                                                 TypeMap map = GetTypeMap (type);
132                                                 return map.Deserialize (this);
133                                         }
134                                 }
135                                 else
136                                         return ReadInstanceDrivenObject ();
137                         }
138                 }
139
140                 Type GetRuntimeType (string name)
141                 {
142                         name = ToRuntimeTypeName (name);
143                         if (serializer.KnownTypes != null)
144                                 foreach (Type t in serializer.KnownTypes)
145                                         if (t.FullName == name)
146                                                 return t;
147                         var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
148                         if (ret != null)
149                                 return ret;
150 #if !NET_2_1 // how to do that in ML?
151                         // We probably have to iterate all the existing
152                         // assemblies that are loaded in current domain.
153                         foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
154                                 ret = ass.GetType (name, false);
155                                 if (ret != null)
156                                         return ret;
157                         }
158 #endif
159                         return null;
160                 }
161
162                 object ReadInstanceDrivenObject ()
163                 {
164                         string type = reader.GetAttribute ("type");
165                         if (type == "object") {
166                                 string runtimeType = reader.GetAttribute ("__type");
167                                 if (runtimeType != null) {
168                                         Type t = GetRuntimeType (runtimeType);
169                                         if (t == null)
170                                                 throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
171                                         return ReadObject (t);
172                                 }
173                         }
174                         string v = reader.ReadElementContentAsString ();
175                         switch (type) {
176                         case "boolean":
177                                 switch (v) {
178                                 case "true":
179                                         return true;
180                                 case "false":
181                                         return false;
182                                 default:
183                                         throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
184                                 }
185                         case "string":
186                                 return v;
187                         case "null":
188                                 if (v != "null")
189                                         throw SerializationError (String.Format ("Invalid JSON null value: {0}", v));
190                                 return null;
191                         case "number":
192                                 int i;
193                                 if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
194                                         return i;
195                                 long l;
196                                 if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
197                                         return l;
198                                 ulong ul;
199                                 if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
200                                         return ul;
201                                 double dbl;
202                                 if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
203                                         return dbl;
204                                 decimal dec;
205                                 if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
206                                         return dec;
207                                 throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
208                         default:
209                                 throw SerializationError (String.Format ("Unexpected type: {0}", type));
210                         }
211                 }
212
213                 string FormatTypeName (Type type)
214                 {
215                         return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
216                 }
217
218                 string ToRuntimeTypeName (string s)
219                 {
220                         int idx = s.IndexOf (":#", StringComparison.Ordinal);
221                         return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
222                 }
223
224                 Type GetCollectionType (Type type)
225                 {
226                         if (type.IsArray)
227                                 return type.GetElementType ();
228                         if (type.IsGenericType) {
229                                 // returns T for ICollection<T>
230                                 Type [] ifaces = type.GetInterfaces ();
231                                 foreach (Type i in ifaces)
232                                         if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (ICollection<>)))
233                                                 return i.GetGenericArguments () [0];
234                         }
235                         if (typeof (IList).IsAssignableFrom (type))
236                                 // return typeof(object) for mere collection.
237                                 return typeof (object);
238                         else
239                                 return null;
240                 }
241
242                 object DeserializeGenericCollection (Type collectionType, Type elementType)
243                 {
244                         reader.ReadStartElement ();
245                         object ret;
246                         if (typeof (IList).IsAssignableFrom (collectionType)) {
247 #if NET_2_1
248                                 Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
249 #else
250                                 Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
251 #endif
252                                 IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
253                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
254                                         if (!reader.IsStartElement ("item"))
255                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
256                                         Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
257                                         object elem = ReadObject (et ?? typeof (object));
258                                         c.Add (elem);
259                                 }
260 #if NET_2_1
261                                 if (collectionType.IsArray) {
262                                         Array array = Array.CreateInstance (elementType, c.Count);
263                                         c.CopyTo (array, 0);
264                                         ret = array;
265                                 }
266                                 else
267                                         ret = c;
268 #else
269                                 ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
270 #endif
271                         } else {
272                                 object c = Activator.CreateInstance (collectionType);
273                                 MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
274                                 if (add == null) {
275                                         var icoll = typeof (ICollection<>).MakeGenericType (elementType);
276                                         if (icoll.IsAssignableFrom (c.GetType ()))
277                                                 add = icoll.GetMethod ("Add");
278                                 }
279                                 
280                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
281                                         if (!reader.IsStartElement ("item"))
282                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
283                                         object elem = ReadObject (elementType);
284                                         add.Invoke (c, new object [] {elem});
285                                 }
286                                 ret = c;
287                         }
288
289                         reader.ReadEndElement ();
290                         return ret;
291                 }
292
293                 TypeMap GetTypeMap (Type type)
294                 {
295                         TypeMap map;
296                         if (!typemaps.TryGetValue (type, out map)) {
297                                 map = TypeMap.CreateTypeMap (type);
298                                 typemaps [type] = map;
299                         }
300                         return map;
301                 }
302
303                 Exception SerializationError (string basemsg)
304                 {
305                         IXmlLineInfo li = reader as IXmlLineInfo;
306                         if (li == null || !li.HasLineInfo ())
307                                 return new SerializationException (basemsg);
308                         else
309                                 return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
310                 }
311         }
312 }