GeoJsonGeometrySerializer.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 System.Collections.Generic;
  17. using System.Linq;
  18. using MongoDB.Bson.IO;
  19. using MongoDB.Bson.Serialization;
  20. using MongoDB.Bson.Serialization.Serializers;
  21. namespace MongoDB.Driver.GeoJsonObjectModel.Serializers
  22. {
  23. /// <summary>
  24. /// Represents a serializer for a GeoJsonGeometry value.
  25. /// </summary>
  26. /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam>
  27. public class GeoJsonGeometrySerializer<TCoordinates> : ClassSerializerBase<GeoJsonGeometry<TCoordinates>> where TCoordinates : GeoJsonCoordinates
  28. {
  29. /// <summary>
  30. /// Gets the actual type.
  31. /// </summary>
  32. /// <param name="context">The context.</param>
  33. /// <returns>The actual type.</returns>
  34. protected override Type GetActualType(BsonDeserializationContext context)
  35. {
  36. var bsonReader = context.Reader;
  37. var bookmark = bsonReader.GetBookmark();
  38. bsonReader.ReadStartDocument();
  39. if (bsonReader.FindElement("type"))
  40. {
  41. var discriminator = bsonReader.ReadString();
  42. bsonReader.ReturnToBookmark(bookmark);
  43. switch (discriminator)
  44. {
  45. case "GeometryCollection": return typeof(GeoJsonGeometryCollection<TCoordinates>);
  46. case "LineString": return typeof(GeoJsonLineString<TCoordinates>);
  47. case "MultiLineString": return typeof(GeoJsonMultiLineString<TCoordinates>);
  48. case "MultiPoint": return typeof(GeoJsonMultiPoint<TCoordinates>);
  49. case "MultiPolygon": return typeof(GeoJsonMultiPolygon<TCoordinates>);
  50. case "Point": return typeof(GeoJsonPoint<TCoordinates>);
  51. case "Polygon": return typeof(GeoJsonPolygon<TCoordinates>);
  52. default:
  53. var message = string.Format("The type field of the GeoJsonGeometry is not valid: '{0}'.", discriminator);
  54. throw new FormatException(message);
  55. }
  56. }
  57. else
  58. {
  59. throw new FormatException("GeoJsonGeometry object is missing the type field.");
  60. }
  61. }
  62. }
  63. }