[System] Fixes UdpClient.Receive with IPv6 endpoint
[mono.git] / mcs / class / System.ServiceModel.Web / System.Runtime.Serialization.Json / JsonSerializationWriter.cs
1 //
2 // JsonSerializationWriter.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 JsonSerializationWriter
41         {
42                 DataContractJsonSerializer serializer;
43                 XmlWriter writer;
44                 int serialized_object_count;
45                 bool always_emit_type;
46                 Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
47                 Type root_type;
48
49                 public JsonSerializationWriter (DataContractJsonSerializer serializer, XmlWriter writer, Type rootType, bool alwaysEmitTypeInformation)
50                 {
51                         this.serializer = serializer;
52                         this.writer = writer;
53                         this.root_type = rootType;
54                         this.always_emit_type = alwaysEmitTypeInformation;
55                 }
56
57                 public XmlWriter Writer {
58                         get { return writer; }
59                 }
60
61                 public void WriteObjectContent (object graph, bool top, bool outputTypeName)
62                 {
63                         if (graph == null) {
64                                 if (top)
65                                         GetTypeMap (root_type); // to make sure to reject invalid contracts
66                                 writer.WriteAttributeString ("type", "null");
67                                 writer.WriteString (null);
68                                 return;
69                         }
70
71                         if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
72                                 throw new SerializationException (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
73
74                         var type = graph.GetType ();
75                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
76                                 type = type.GetGenericArguments () [0];
77
78                         switch (Type.GetTypeCode (type)) {
79                         case TypeCode.Char:
80                         case TypeCode.String:
81                                 writer.WriteString (graph.ToString ());
82                                 break;
83                         case TypeCode.Single:
84                         case TypeCode.Double:
85                                 writer.WriteAttributeString ("type", "number");
86                                 writer.WriteString (((IFormattable) graph).ToString ("R", CultureInfo.InvariantCulture));
87                                 break;
88                         case TypeCode.Byte:
89                         case TypeCode.SByte:
90                         case TypeCode.Int16:
91                         case TypeCode.Int32:
92                         case TypeCode.Int64:
93                         case TypeCode.UInt16:
94                         case TypeCode.UInt32:
95                         case TypeCode.UInt64:
96                         case TypeCode.Decimal:
97                                 writer.WriteAttributeString ("type", "number");
98                                 if (type.IsEnum)
99                                         graph = ((IConvertible) graph).ToType (Enum.GetUnderlyingType (type), CultureInfo.InvariantCulture);
100                                 writer.WriteString (((IFormattable) graph).ToString ("G", CultureInfo.InvariantCulture));
101                                 break;
102                         case TypeCode.Boolean:
103                                 writer.WriteAttributeString ("type", "boolean");
104                                 if ((bool) graph)
105                                         writer.WriteString ("true");
106                                 else
107                                         writer.WriteString ("false");
108                                 break;
109                         case TypeCode.DateTime:
110                                 writer.WriteString (String.Format (CultureInfo.InvariantCulture, "/Date({0})/", (long) ((DateTime) graph).Subtract (new DateTime (1970, 1, 1)).TotalMilliseconds));
111                                 break;
112                         default:
113                                 if (graph is Guid) {
114                                         goto case TypeCode.String;
115                                 } else if (graph is Uri) {
116                                         goto case TypeCode.String;
117                                 } else if (graph is XmlQualifiedName) {
118                                         XmlQualifiedName qn = (XmlQualifiedName) graph;
119                                         writer.WriteString (qn.Name);
120                                         writer.WriteString (":");
121                                         writer.WriteString (qn.Namespace);
122                                 } else if (TypeMap.IsDictionary (type)) {
123                                         writer.WriteAttributeString ("type", "array");
124                                         bool otn = !(graph is Array && type.GetElementType () != typeof (object));
125                                         var d = graph as IDictionary;
126                                         if (d != null) {
127                                                 // Optimize the IDictionary case to avoid reflection
128                                                 foreach (object k in d.Keys)
129                                                         WriteItem (k, d [k], otn);
130                                         } else {
131                                                 // we can't typecast to IDictionary<,> and can't use dynamic for iOS support
132                                                 var itemGetter = GetDictionaryProperty (type, "Item");
133                                                 var keysGetter = GetDictionaryProperty (type, "Keys");
134                                                 var argarr = new object [1];
135                                                 foreach (object o in (IEnumerable) keysGetter.GetValue (graph, null)) {
136                                                         argarr [0] = o;
137                                                         WriteItem (o, itemGetter.GetValue (graph, argarr), otn);
138                                                 }
139                                         }
140                                 } else if (graph is Array || TypeMap.IsEnumerable (type)) {
141                                         writer.WriteAttributeString ("type", "array");
142                                         foreach (object o in (IEnumerable) graph) {
143                                                 writer.WriteStartElement ("item");
144                                                 // when it is typed, then no need to output "__type"
145                                                 WriteObjectContent (o, false, !(graph is Array && type.GetElementType () != typeof (object)));
146                                                 writer.WriteEndElement ();
147                                         }
148                                 } else { // object
149                                         TypeMap tm = GetTypeMap (type);
150                                         if (tm != null) {
151                                                 // FIXME: I'm not sure how it is determined whether __type is written or not...
152                                                 if (outputTypeName || always_emit_type)
153                                                         writer.WriteAttributeString ("__type", FormatTypeName (type));
154                                                 tm.Serialize (this, graph, "object");
155                                         }
156                                         else
157                                                 // it does not emit type="object" (as the graph is regarded as a string)
158 //                                              writer.WriteString (graph.ToString ());
159 throw new InvalidDataContractException (String.Format ("Type {0} cannot be serialized by this JSON serializer", type));
160                                 }
161                                 break;
162                         }
163                 }
164
165                 void WriteItem (object key, object value, bool outputTypeName)
166                 {
167                         writer.WriteStartElement ("item");
168                         writer.WriteAttributeString ("type", "object");
169                         // outputting a KeyValuePair as <Key .. /><Value ... />
170                         writer.WriteStartElement ("Key");
171                         WriteObjectContent (key, false, outputTypeName);
172                         writer.WriteEndElement ();
173                         writer.WriteStartElement ("Value");
174                         WriteObjectContent (value, false, outputTypeName);
175                         writer.WriteEndElement ();
176                         writer.WriteEndElement ();
177                 }
178
179                 PropertyInfo GetDictionaryProperty (Type type, string propertyName)
180                 {
181                         var p = type.GetProperty (propertyName);
182                         if (p != null)
183                                 return p;
184                         // check explicit - but the generic names might differ, e.g. TKey,TValue vs T,V
185                         var ap = type.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic);
186                         foreach (var cp in ap) {
187                                 if (!cp.Name.EndsWith (propertyName, StringComparison.Ordinal))
188                                         continue;
189                                 if (cp.Name.StartsWith ("System.Collections.Generic.IDictionary<", StringComparison.Ordinal))
190                                         return cp;
191                         }
192                         return null;
193                 }
194
195                 string FormatTypeName (Type type)
196                 {
197                         return String.Format ("{0}:#{1}", type.Name, type.Namespace);
198                 }
199
200                 TypeMap GetTypeMap (Type type)
201                 {
202                         TypeMap map;
203                         if (!typemaps.TryGetValue (type, out map)) {
204                                 map = TypeMap.CreateTypeMap (type);
205                                 typemaps [type] = map;
206                         }
207                         return map;
208                 }
209         }
210 }