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