XmlObjectSerializerWriteContextComplexJson.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Xml;
  5. using System.Reflection;
  6. using System.ServiceModel;
  7. using System.Collections;
  8. namespace System.Runtime.Serialization.Json
  9. {
  10. #if USE_REFEMIT
  11. public class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
  12. #else
  13. internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
  14. #endif
  15. {
  16. EmitTypeInformation emitXsiType;
  17. bool perCallXsiTypeAlreadyEmitted;
  18. bool useSimpleDictionaryFormat;
  19. public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
  20. : base(serializer,
  21. serializer.MaxItemsInObjectGraph,
  22. new StreamingContext(StreamingContextStates.All),
  23. serializer.IgnoreExtensionDataObject)
  24. {
  25. this.emitXsiType = serializer.EmitTypeInformation;
  26. this.rootTypeDataContract = rootTypeDataContract;
  27. this.serializerKnownTypeList = serializer.knownTypeList;
  28. this.dataContractSurrogate = serializer.DataContractSurrogate;
  29. this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
  30. this.useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
  31. }
  32. internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
  33. {
  34. return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
  35. }
  36. internal IList<Type> SerializerKnownTypeList
  37. {
  38. get
  39. {
  40. return this.serializerKnownTypeList;
  41. }
  42. }
  43. public bool UseSimpleDictionaryFormat
  44. {
  45. get
  46. {
  47. return this.useSimpleDictionaryFormat;
  48. }
  49. }
  50. internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
  51. {
  52. return false;
  53. }
  54. internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
  55. {
  56. return false;
  57. }
  58. internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
  59. {
  60. }
  61. protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
  62. {
  63. if (this.emitXsiType != EmitTypeInformation.Never)
  64. {
  65. if (string.IsNullOrEmpty(dataContractNamespace))
  66. {
  67. WriteTypeInfo(writer, dataContractName);
  68. }
  69. else
  70. {
  71. WriteTypeInfo(writer, string.Concat(dataContractName, JsonGlobals.NameValueSeparatorString, TruncateDefaultDataContractNamespace(dataContractNamespace)));
  72. }
  73. }
  74. }
  75. internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace)
  76. {
  77. if (!string.IsNullOrEmpty(dataContractNamespace))
  78. {
  79. if (dataContractNamespace[0] == '#')
  80. {
  81. return string.Concat("\\", dataContractNamespace);
  82. }
  83. else if (dataContractNamespace[0] == '\\')
  84. {
  85. return string.Concat("\\", dataContractNamespace);
  86. }
  87. else if (dataContractNamespace.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal))
  88. {
  89. return string.Concat("#", dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength));
  90. }
  91. }
  92. return dataContractNamespace;
  93. }
  94. static bool RequiresJsonTypeInfo(DataContract contract)
  95. {
  96. return (contract is ClassDataContract);
  97. }
  98. void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation)
  99. {
  100. writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation);
  101. }
  102. protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
  103. {
  104. if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) &&
  105. object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) ||
  106. (contract.Name.Value == declaredContract.Name.Value &&
  107. contract.Namespace.Value == declaredContract.Namespace.Value)) &&
  108. (contract.UnderlyingType != Globals.TypeOfObjectArray) &&
  109. (this.emitXsiType != EmitTypeInformation.Never))
  110. {
  111. // We always deserialize collections assigned to System.Object as object[]
  112. // Because of its common and JSON-specific nature,
  113. // we don't want to validate known type information for object[]
  114. // Don't validate known type information when emitXsiType == Never because
  115. // known types are not used without type information in the JSON
  116. if (RequiresJsonTypeInfo(contract))
  117. {
  118. perCallXsiTypeAlreadyEmitted = true;
  119. WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value);
  120. }
  121. else
  122. {
  123. // check if the declared type is System.Enum and throw because
  124. // __type information cannot be written for enums since it results in invalid JSON.
  125. // Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum.
  126. if (declaredContract.UnderlyingType == typeof(Enum))
  127. {
  128. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException
  129. (SR.GetString(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType)));
  130. }
  131. }
  132. // Return true regardless of whether we actually wrote __type information
  133. // E.g. We don't write __type information for enums, but we still want verifyKnownType
  134. // to be true for them.
  135. return true;
  136. }
  137. return false;
  138. }
  139. #if USE_REFEMIT
  140. public void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
  141. #else
  142. internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
  143. #endif
  144. {
  145. Type objType = obj.GetType();
  146. SerializationInfo serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter);
  147. GetObjectData(obj, serInfo, GetStreamingContext());
  148. if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
  149. {
  150. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType))));
  151. }
  152. else
  153. {
  154. base.WriteSerializationInfo(xmlWriter, objType, serInfo);
  155. }
  156. }
  157. #if USE_REFEMIT
  158. public static DataContract GetRevisedItemContract(DataContract oldItemContract)
  159. #else
  160. internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
  161. #endif
  162. {
  163. if ((oldItemContract != null) &&
  164. oldItemContract.UnderlyingType.IsGenericType &&
  165. (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
  166. {
  167. return DataContract.GetDataContract(oldItemContract.UnderlyingType);
  168. }
  169. return oldItemContract;
  170. }
  171. protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
  172. {
  173. JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract);
  174. if (emitXsiType == EmitTypeInformation.Always && !perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract))
  175. {
  176. WriteTypeInfo(xmlWriter, jsonDataContract.TypeName);
  177. }
  178. perCallXsiTypeAlreadyEmitted = false;
  179. DataContractJsonSerializer.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle);
  180. }
  181. protected override void WriteNull(XmlWriterDelegator xmlWriter)
  182. {
  183. DataContractJsonSerializer.WriteJsonNull(xmlWriter);
  184. }
  185. #if USE_REFEMIT
  186. public XmlDictionaryString CollectionItemName
  187. #else
  188. internal XmlDictionaryString CollectionItemName
  189. #endif
  190. {
  191. get { return JsonGlobals.itemDictionaryString; }
  192. }
  193. #if USE_REFEMIT
  194. public static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index)
  195. #else
  196. internal static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index)
  197. #endif
  198. {
  199. xmlWriter.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString);
  200. xmlWriter.WriteAttributeString(null, JsonGlobals.itemString, null, memberNames[index].Value);
  201. }
  202. internal override void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode)
  203. {
  204. Type dataType = dataNode.DataType;
  205. if (dataType == Globals.TypeOfClassDataNode ||
  206. dataType == Globals.TypeOfISerializableDataNode)
  207. {
  208. xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
  209. base.WriteExtensionDataTypeInfo(xmlWriter, dataNode);
  210. }
  211. else if (dataType == Globals.TypeOfCollectionDataNode)
  212. {
  213. xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.arrayString);
  214. // Don't write __type for collections
  215. }
  216. else if (dataType == Globals.TypeOfXmlDataNode)
  217. {
  218. // Don't write type or __type for XML types because we serialize them to strings
  219. }
  220. else if ((dataType == Globals.TypeOfObject) && (dataNode.Value != null))
  221. {
  222. DataContract dc = GetDataContract(dataNode.Value.GetType());
  223. if (RequiresJsonTypeInfo(dc))
  224. {
  225. base.WriteExtensionDataTypeInfo(xmlWriter, dataNode);
  226. }
  227. }
  228. }
  229. protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
  230. {
  231. DataContract dataContract;
  232. bool verifyKnownType = false;
  233. bool isDeclaredTypeInterface = declaredType.IsInterface;
  234. if (isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
  235. {
  236. dataContract = GetDataContract(declaredTypeHandle, declaredType);
  237. }
  238. else if (declaredType.IsArray) // If declared type is array do not write __serverType. Instead write__serverType for each item
  239. {
  240. dataContract = GetDataContract(declaredTypeHandle, declaredType);
  241. }
  242. else
  243. {
  244. dataContract = GetDataContract(objectTypeHandle, objectType);
  245. DataContract declaredTypeContract = (declaredTypeID >= 0)
  246. ? GetDataContract(declaredTypeID, declaredTypeHandle)
  247. : GetDataContract(declaredTypeHandle, declaredType);
  248. verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
  249. HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
  250. }
  251. if (isDeclaredTypeInterface)
  252. {
  253. VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
  254. }
  255. SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
  256. }
  257. static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType)
  258. {
  259. Type contractType = contract.GetType();
  260. if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType))
  261. {
  262. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
  263. }
  264. if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType))
  265. {
  266. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
  267. }
  268. }
  269. void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType)
  270. {
  271. if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract))
  272. {
  273. if (verifyKnownType)
  274. {
  275. VerifyType(dataContract, declaredType);
  276. verifyKnownType = false;
  277. }
  278. if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary)
  279. {
  280. // Convert non-generic dictionary to generic dictionary
  281. IDictionary dictionaryObj = obj as IDictionary;
  282. Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>();
  283. foreach (DictionaryEntry entry in dictionaryObj)
  284. {
  285. genericDictionaryObj.Add(entry.Key, entry.Value);
  286. }
  287. obj = genericDictionaryObj;
  288. }
  289. dataContract = GetDataContract(Globals.TypeOfIEnumerable);
  290. }
  291. }
  292. internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
  293. {
  294. bool verifyKnownType = false;
  295. Type declaredType = rootTypeDataContract.UnderlyingType;
  296. bool isDeclaredTypeInterface = declaredType.IsInterface;
  297. if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
  298. && !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
  299. {
  300. verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
  301. HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
  302. }
  303. if (isDeclaredTypeInterface)
  304. {
  305. VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
  306. }
  307. SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
  308. }
  309. void VerifyType(DataContract dataContract, Type declaredType)
  310. {
  311. bool knownTypesAddedInCurrentScope = false;
  312. if (dataContract.KnownDataContracts != null)
  313. {
  314. scopedKnownTypes.Push(dataContract.KnownDataContracts);
  315. knownTypesAddedInCurrentScope = true;
  316. }
  317. if (!IsKnownType(dataContract, declaredType))
  318. {
  319. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
  320. }
  321. if (knownTypesAddedInCurrentScope)
  322. {
  323. scopedKnownTypes.Pop();
  324. }
  325. }
  326. internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
  327. {
  328. DataContract dataContract = base.GetDataContract(typeHandle, type);
  329. DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
  330. return dataContract;
  331. }
  332. internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
  333. {
  334. DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
  335. DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
  336. return dataContract;
  337. }
  338. internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
  339. {
  340. DataContract dataContract = base.GetDataContract(id, typeHandle);
  341. DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
  342. return dataContract;
  343. }
  344. internal static DataContract ResolveJsonDataContractFromRootDataContract(XmlObjectSerializerContext context, XmlQualifiedName typeQName, DataContract rootTypeDataContract)
  345. {
  346. if (rootTypeDataContract.StableName == typeQName)
  347. return rootTypeDataContract;
  348. CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract;
  349. while (collectionContract != null)
  350. {
  351. DataContract itemContract;
  352. if (collectionContract.ItemType.IsGenericType
  353. && collectionContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
  354. {
  355. itemContract = context.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
  356. }
  357. else
  358. {
  359. itemContract = context.GetDataContract(context.GetSurrogatedType(collectionContract.ItemType));
  360. }
  361. if (itemContract.StableName == typeQName)
  362. {
  363. return itemContract;
  364. }
  365. collectionContract = itemContract as CollectionDataContract;
  366. }
  367. return null;
  368. }
  369. protected override DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName)
  370. {
  371. return XmlObjectSerializerWriteContextComplexJson.ResolveJsonDataContractFromRootDataContract(this, typeQName, rootTypeDataContract);
  372. }
  373. }
  374. }