GeoJsonObjectSerializer.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using MongoDB.Bson.IO;
  17. using MongoDB.Bson.Serialization;
  18. using MongoDB.Bson.Serialization.Serializers;
  19. namespace MongoDB.Driver.GeoJsonObjectModel.Serializers
  20. {
  21. /// <summary>
  22. /// Represents a serializer for a GeoJson object.
  23. /// </summary>
  24. /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam>
  25. public class GeoJsonObjectSerializer<TCoordinates> : ClassSerializerBase<GeoJsonObject<TCoordinates>> where TCoordinates : GeoJsonCoordinates
  26. {
  27. // protected methods
  28. /// <summary>
  29. /// Gets the actual type.
  30. /// </summary>
  31. /// <param name="context">The context.</param>
  32. /// <returns>The actual type.</returns>
  33. protected override Type GetActualType(BsonDeserializationContext context)
  34. {
  35. var bsonReader = context.Reader;
  36. var bookmark = bsonReader.GetBookmark();
  37. bsonReader.ReadStartDocument();
  38. if (bsonReader.FindElement("type"))
  39. {
  40. var discriminator = bsonReader.ReadString();
  41. bsonReader.ReturnToBookmark(bookmark);
  42. switch (discriminator)
  43. {
  44. case "Feature": return typeof(GeoJsonFeature<TCoordinates>);
  45. case "FeatureCollection": return typeof(GeoJsonFeatureCollection<TCoordinates>);
  46. case "GeometryCollection": return typeof(GeoJsonGeometryCollection<TCoordinates>);
  47. case "LineString": return typeof(GeoJsonLineString<TCoordinates>);
  48. case "MultiLineString": return typeof(GeoJsonMultiLineString<TCoordinates>);
  49. case "MultiPoint": return typeof(GeoJsonMultiPoint<TCoordinates>);
  50. case "MultiPolygon": return typeof(GeoJsonMultiPolygon<TCoordinates>);
  51. case "Point": return typeof(GeoJsonPoint<TCoordinates>);
  52. case "Polygon": return typeof(GeoJsonPolygon<TCoordinates>);
  53. default:
  54. var message = string.Format("The type field of the GeoJsonObject is not valid: '{0}'.", discriminator);
  55. throw new FormatException(message);
  56. }
  57. }
  58. else
  59. {
  60. throw new FormatException("GeoJsonObject is missing the type field.");
  61. }
  62. }
  63. }
  64. }