예제 #1
0
        public void deserialize_a_json_fragment_should_throws_an_error()
        {
            var reader     = new JsonTextReader(new StringReader(serializedGeometries));
            var serializer = GeoJsonSerializer.Create(factory);

            Assert.Throws <JsonReaderException>(() => serializer.Deserialize <Geometry[]>(reader));
        }
예제 #2
0
        public void Test3DPointSerialization()
        {
            var factory  = GeometryFactory.Default;
            var point1   = factory.CreatePoint(new CoordinateZM(1, 2, 3, 4));
            var feature1 = new Feature(point1, null);

            Feature feature2;

            using (var ms = new MemoryStream())
            {
                var serializer = GeoJsonSerializer.Create(factory, 3);
                using (var writer = new StreamWriter(ms, Encoding.UTF8, 1024, true))
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        serializer.Serialize(jsonWriter, feature1);
                    }

                ms.Position = 0;
                using (var reader = new StreamReader(ms, Encoding.UTF8, true, 1024, true))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        feature2 = serializer.Deserialize <Feature>(jsonReader);
                    }
            }

            Assert.That(feature2.Geometry, Is.InstanceOf <Point>());
            var point2 = (Point)feature2.Geometry;

            Assert.That(point2.CoordinateSequence.HasZ);
            Assert.That(CoordinateSequences.IsEqual(point1.CoordinateSequence, point2.CoordinateSequence));

            // GeoJSON doesn't support M, so there should NOT be an M present in round-trip.
            Assert.That(!point2.CoordinateSequence.HasM);
        }
예제 #3
0
        public static List <CoordinateZ> CoordinateListFromGeoJsonFeatureCollectionWithLinestring(string geoJson)
        {
            if (string.IsNullOrWhiteSpace(geoJson))
            {
                return(new List <CoordinateZ>());
            }

            var serializer = GeoJsonSerializer.Create(Wgs84GeometryFactory(), 3);

            using var stringReader = new StringReader(geoJson);
            using var jsonReader   = new JsonTextReader(stringReader);
            var featureCollection = serializer.Deserialize <FeatureCollection>(jsonReader);

            if (featureCollection == null || featureCollection.Count < 1)
            {
                return(new List <CoordinateZ>());
            }

            var possibleLine = featureCollection.FirstOrDefault(x => x.Geometry is LineString);

            if (possibleLine == null)
            {
                return(new List <CoordinateZ>());
            }

            var geoLine = (LineString)possibleLine.Geometry;

            return(geoLine.Coordinates.Select(x => new CoordinateZ(x.X, x.Y, x.Z)).ToList());
        }
예제 #4
0
        public void TestGeometryConverterAttribute()
        {
            var myModelItem = new MyModelItem();

            myModelItem.Geom = new global::NetTopologySuite.Geometries.MultiLineString(
                new NetTopologySuite.Geometries.LineString[]
            {
                new global::NetTopologySuite.Geometries.LineString(new[]
                                                                   { new NetTopologySuite.Geometries.Coordinate(10, 10), new NetTopologySuite.Geometries.Coordinate(20, 10) }),
                new global::NetTopologySuite.Geometries.LineString(new[]
                                                                   { new NetTopologySuite.Geometries.Coordinate(10, 11), new NetTopologySuite.Geometries.Coordinate(20, 11) }),
                new global::NetTopologySuite.Geometries.LineString(new[]
                                                                   { new NetTopologySuite.Geometries.Coordinate(10, 12), new NetTopologySuite.Geometries.Coordinate(20, 12) })
            });

            var s = GeoJsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings(),
                                             NtsGeometryServices.Instance.CreateGeometryFactory(31467));
            var sb = new System.Text.StringBuilder();

            s.Serialize(new Newtonsoft.Json.JsonTextWriter(new System.IO.StringWriter(sb)), myModelItem);
            System.Console.WriteLine(sb.ToString());

            var myModelItem2 =
                s.Deserialize <MyModelItem>(
                    new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(sb.ToString())));
        }
        public void TestOutputDimension()
        {
            var coords = new[]
            {
                new Coordinate(0.001, 0.001, 3),
                new Coordinate(10.1, 0.002, 3),
                new Coordinate(10, 10.1, 3),
                new Coordinate(0.05, 9.999, 3),
                new Coordinate(0.001, 0.001, 3)
            };

            // Create a factory with scale = 10
            var factory = new GeometryFactory(new PrecisionModel(10), 4326);

            // Creating the polygon with the above factory
            var polygon = factory.CreatePolygon(coords);

            var serializer2 = GeoJsonSerializer.Create(factory, 2);
            var serializer3 = GeoJsonSerializer.Create(factory, 3);
            var writer      = new StringWriter();

            serializer2.Serialize(writer, polygon);

            string json2 = writer.ToString();

            Assert.That(json2, Is.EqualTo("{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[10.1,0.0],[10.0,10.1],[0.1,10.0],[0.0,0.0]]]}"));

            writer = new StringWriter();
            serializer3.Serialize(writer, polygon);
            string json3 = writer.ToString();

            Assert.That(json3, Is.EqualTo("{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0,3.0],[10.1,0.0,3.0],[10.0,10.1,3.0],[0.1,10.0,3.0],[0.0,0.0,3.0]]]}"));
        }
예제 #6
0
        public void TestIssue83()
        {
            var geoJson = @"{ ""type"": ""Feature"", 
                              ""geometry"": { ""type"": ""Point"", ""coordinates"": [10.0, 60.0] }, 
                              ""id"": 1, 
                             ""properties"": { ""Name"": ""test"" } }";

            var     s = GeoJsonSerializer.Create(GeometryFactory.Default);
            Feature f = null;

            Assert.DoesNotThrow(() =>
                                f = s.Deserialize <Feature>(new JsonTextReader(new StringReader(geoJson)))
                                );

            Assert.IsNotNull(f, "f != null");
            Assert.IsTrue(FeatureExtensions.HasID(f), "f.HasID()");
            Assert.AreEqual(1, FeatureExtensions.ID(f), "f.ID != 1");

            var sb = new StringBuilder();
            var tw = new JsonTextWriter(new StringWriter(sb));

            s.Serialize(tw, f);
            var geoJsonRes = sb.ToString();

            CompareJson(geoJson, geoJsonRes);
        }
        public void TestInputDimension()
        {
            var coords = new[]
            {
                new Coordinate(0.001, 0.001),
                new Coordinate(10.1, 0.002),
                new Coordinate(10, 10.1),
                new Coordinate(0.05, 9.999),
                new Coordinate(0.001, 0.001)
            };

            // Create a factory with scale = 10
            var factory = new GeometryFactory(new PrecisionModel(10), 4326);

            var serializer3 = GeoJsonSerializer.Create(factory, 3);
            var reader      = new JsonTextReader(new StringReader("{\"type\":\"Polygon\",\"coordinates\":[[[0.001,0.001,3.0],[10.1,0.002,3.0],[10.0,10.1,3.0],[0.05,9.999,3.0],[0.001,0.001,3.0]]]}"));
            var geom        = serializer3.Deserialize <IGeometry>(reader);

            Assert.That(geom.AsText(), Is.EqualTo("POLYGON ((0 0 3, 10.1 0 3, 10 10.1 3, 0.1 10 3, 0 0 3))"));

            var serializer2 = GeoJsonSerializer.Create(factory, 2);

            reader = new JsonTextReader(new StringReader("{\"type\":\"Polygon\",\"coordinates\":[[[0.001,0.001,3.0],[10.1,0.002,3.0],[10.0,10.1,3.0],[0.05,9.999,3.0],[0.001,0.001,3.0]]]}"));
            geom   = serializer2.Deserialize <IGeometry>(reader);
            Assert.That(geom.AsText(), Is.EqualTo("POLYGON ((0 0, 10.1 0, 10 10.1, 0.1 10, 0 0))"));
        }
        /// <summary>
        /// Creates a GeoJson from all ProjectGeometries in the current project (session has to be set)
        /// </summary>
        /// <returns>GeoJson string</returns>
        private string createGeoJson()
        {
            string projectId = HttpContext.Session.GetString("Project");

            if (projectId == null)
            {
                return("");
            }

            //TODO chb
            //Project myProject = db.Projects.Include(m => m.Geometries).Where(m => m.ProjectId == new Guid(projectId)).FirstOrDefault();
            Project myProject = db.Projects
                                .Include(p => p.ProjectGroups).ThenInclude(m => m.Geometries)
                                .Where(m => m.ProjectId == new Guid(projectId)).FirstOrDefault();

            if (myProject == null)
            {
                return("");
            }

            if (myProject != null)
            {
                NetTopologySuite.Features.FeatureCollection featureCollection = new NetTopologySuite.Features.FeatureCollection();

                //TODO chb
                //foreach (ReferenceGeometry g in myProject.Geometries.Where(m => m.StatusId != StatusEnum.deleted))
                foreach (ReferenceGeometry g in myProject.ProjectGroups.SelectMany(pg => pg.Geometries).Where(g => g.StatusId != StatusEnum.deleted))
                {
                    NetTopologySuite.Features.Feature f = null;
                    if (g.Point != null)
                    {
                        f = getFeature(g, GeomType.Point);
                    }
                    if (g.Line != null)
                    {
                        f = getFeature(g, GeomType.Line);
                    }
                    if (g.Polygon != null)
                    {
                        f = getFeature(g, GeomType.Polygon);
                    }
                    if (f != null)
                    {
                        featureCollection.Add(f);
                    }
                }


                var jsonSerializer = GeoJsonSerializer.Create();
                var sw             = new System.IO.StringWriter();
                jsonSerializer.Serialize(sw, featureCollection);

                return(sw.ToString());
            }
            else
            {
                return(null);// "No project found";
            }
        }
예제 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddApiVersioning(
                options =>
            {
                options.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(
                options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddControllers()
            .AddControllersAsServices()
            .AddMvcOptions(config =>
            {
                config.CacheProfiles.Add("Default1hr", new Microsoft.AspNetCore.Mvc.CacheProfile()
                {
                    Duration = 3600,
                    Location = Microsoft.AspNetCore.Mvc.ResponseCacheLocation.Any,
                    NoStore  = true
                });

                //Filtros
                config.Filters.Add(typeof(HttpGlobalExceptionFilter));
                config.Filters.Add(typeof(ValidateModelStateFilter));

                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Point)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(LineString)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiLineString)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiPolygon)));
            })
            .AddFluentValidation()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

                foreach (var converter in GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel())).Converters)
                {
                    options.SerializerSettings.Converters.Add(converter);
                }
            });

            services.AddRedisCache(Configuration.GetSection("Redis:ConnectionString").Get <string>());

            services.AddOpenTracingAndJaeger();

            services.AddSwagger();

            AddAuthentication(services);
            RegisterDbContexts(services);

            services.AddMediatR(typeof(Startup).Assembly);
        }
예제 #10
0
        public T DeSerialise <T>(string payload)
        {
            var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
            var serializer      = GeoJsonSerializer.Create(geometryFactory);
            var data            = serializer.Deserialize <T>(new JsonTextReader(new StringReader(payload)));

            return(data);
        }
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     if (value != null)
     {
         var feature = new Feature(value as Geometry, new AttributesTable());
         GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel(), SRID)).Serialize(writer, feature);
     }
 }
예제 #12
0
        public static string GetGeojson(FeatureCollection features)
        {
            var serializer = GeoJsonSerializer.Create();
            var writer     = new StringWriter();

            serializer.Serialize(writer, features);
            return(writer.ToString());
        }
예제 #13
0
        public string Convert(Geometry sourceMember, ResolutionContext context)
        {
            var serializer = GeoJsonSerializer.Create();
            var sw         = new StringWriter();
            var geofeature = new Feature(sourceMember, new AttributesTable());

            serializer.Serialize(sw, geofeature, typeof(Feature));
            return(sw.ToString());
        }
예제 #14
0
        public void deserialize_a_valid_json_should_return_a_geometrycollection()
        {
            var reader     = new JsonTextReader(new StringReader(serializedCollection));
            var serializer = GeoJsonSerializer.Create(factory);
            var actual     = serializer.Deserialize <GeometryCollection>(reader);

            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.EqualsExact(collection), Is.True);
        }
예제 #15
0
        public string Serialise <T>(GeometryFactory geometryFactory, T tripStatusMessage)
        {
            var stringBuilder = new StringBuilder();
            var serializer    = GeoJsonSerializer.Create(geometryFactory);

            serializer.Serialize(new JsonTextWriter(new StringWriter(stringBuilder)), tripStatusMessage,
                                 typeof(T));
            return(stringBuilder.ToString());
        }
예제 #16
0
        public void feature_collection_is_serialized_as_geojson_when_type_is_placed_as_first_property()
        {
            const string data       = @"{ ""type"": ""FeatureCollection"", ""features"": [] }";
            var          serializer = GeoJsonSerializer.Create();
            var          reader     = new JsonTextReader(new StringReader(data));
            var          fc         = serializer.Deserialize <FeatureCollection>(reader);

            Assert.That(fc, Is.Not.Null);
            Assert.That(fc.Count, Is.EqualTo(0));
        }
예제 #17
0
 public GeoJsonNetSerializer(IConnectionSettingsValues settings, GeometryFactory geometryFactory) : base(settings)
 {
     OverwriteDefaultSerializers((s, cvs) =>
     {
         foreach (var converter in GeoJsonSerializer.Create(geometryFactory, 3).Converters)
         {
             s.Converters.Add(converter);
         }
     });
 }
예제 #18
0
        private string ToGeoJson(IEnumerable <KeyValuePair <int, Earthquake> > earthquakes)
        {
            FeatureCollection featureCollection = ToFeatureCollection(earthquakes);

            var serializer = GeoJsonSerializer.Create();

            using var stringWriter = new StringWriter();
            using var jsonWriter   = new JsonTextWriter(stringWriter);
            serializer.Serialize(jsonWriter, featureCollection);
            return(stringWriter.ToString());
        }
        public void TestInputPrecision()
        {
            // Create a factory with scale = 10
            var factory = new GeometryFactory(new PrecisionModel(10), 4326);

            var serializer = GeoJsonSerializer.Create(factory);
            var reader     = new JsonTextReader(new StringReader("{\"type\":\"Polygon\",\"coordinates\":[[[0.001,0.001],[10.1,0.002],[10.0,10.1],[0.05,9.999],[0.001,0.001]]]}"));
            var geom       = serializer.Deserialize <IGeometry>(reader);

            Assert.That(geom.AsText(), Is.EqualTo("POLYGON ((0 0, 10.1 0, 10 10.1, 0.1 10, 0 0))"));
        }
        public static List <Geometry> LineContentToGeometries(LineContent content)
        {
            var serializer = GeoJsonSerializer.Create(SpatialHelpers.Wgs84GeometryFactory(), 3);

            using var stringReader = new StringReader(content.Line);
            using var jsonReader   = new JsonTextReader(stringReader);
            var featureCollection = serializer.Deserialize <FeatureCollection>(jsonReader);

            return(featureCollection.Select(x => SpatialHelpers.Wgs84GeometryFactory().CreateGeometry(x.Geometry))
                   .ToList());
        }
예제 #21
0
        public void GeoJsonDeserializeOkUsingGeoJsonSerializerCreate()
        {
            Exception ex = null;

            try
            {
                TestIssue176(GeoJsonSerializer.Create());
            }
            catch (JsonException e) { ex = e; }
            Assert.IsNull(ex);
        }
 /// <summary>
 /// Converts <see cref="byte"/> array to <see cref="FeatureCollection"/>
 /// </summary>
 /// <param name="featureCollectionContent">The <see cref="byte"/> array</param>
 /// <returns>The <see cref="FeatureCollection"/></returns>
 public static FeatureCollection ToFeatureCollection(this byte[] featureCollectionContent)
 {
     using (var stream = new MemoryStream(featureCollectionContent))
     {
         var serializer = GeoJsonSerializer.Create(new GeometryFactory(), 3);
         using (var streamReader = new StreamReader(stream))
             using (var jsonTextReader = new JsonTextReader(streamReader))
             {
                 return(serializer.Deserialize <FeatureCollection>(jsonTextReader));
             }
     }
 }
        public virtual string GetGeoJsonCoordinate()
        {
            var lineString = GetLineString();
            var serializer = GeoJsonSerializer.Create();

            using (var stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, lineString);
                var geoJson = stringWriter.ToString();
                return(JObject.Parse(geoJson)["coordinates"].ToString(Formatting.None));
            };
        }
예제 #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddApiVersioning(
                options =>
            {
                options.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(
                options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });


            services.AddControllers()
            .AddControllersAsServices()
            .AddMvcOptions(config =>
            {
                //Filtros
                config.Filters.Add(typeof(HttpGlobalExceptionFilter));
                config.Filters.Add(typeof(ValidateModelStateFilter));

                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Point)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(LineString)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiLineString)));
                config.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiPolygon)));
            })
            .ConfigureFluentValidation()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

                foreach (var converter in GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel())).Converters)
                {
                    options.SerializerSettings.Converters.Add(converter);
                }
            });

            services.AddMediatR(typeof(Startup));
            services.AddElmah(Configuration);
            services.AddSwagger();

            services.ConfigureEventoSourcingMongoDb(Configuration);

            AddAuthentication(services);
            RegisterDbContexts(services);

            // return RegisterServices(services);
        }
예제 #25
0
 /// <summary>
 /// Convers <see cref="FeatureCollection"/> to <see cref="byte"/> array
 /// </summary>
 /// <param name="featureCollection">The <see cref="FeatureCollection"/></param>
 /// <returns>The <see cref="byte"/> array</returns>
 public static byte[] ToBytes(this FeatureCollection featureCollection)
 {
     using (var outputStream = new MemoryStream())
     {
         var writer     = new StreamWriter(outputStream);
         var jsonWriter = new JsonTextWriter(writer);
         var serializer = GeoJsonSerializer.Create(new GeometryFactory(), 3);
         serializer.Serialize(jsonWriter, featureCollection);
         jsonWriter.Flush();
         return(outputStream.ToArray());
     }
 }
예제 #26
0
        public void serialize_a_geometrycollection_should_return_a_valid_json()
        {
            var sb         = new StringBuilder();
            var writer     = new JsonTextWriter(new StringWriter(sb));
            var serializer = GeoJsonSerializer.Create();

            serializer.Serialize(writer, collection);
            string actual = sb.ToString();

            Console.WriteLine(actual);
            Assert.That(actual, Is.EqualTo(serializedCollection));
        }
        private static IFeature SandD(IFeature input)
        {
            var s = GeoJsonSerializer.Create(
                new JsonSerializerSettings
            {
                NullValueHandling   = NullValueHandling.Ignore,
                FloatFormatHandling = FloatFormatHandling.DefaultValue,
                FloatParseHandling  = FloatParseHandling.Double
            }, input.Geometry.Factory ?? GeometryFactory.Default);
            var sb = new StringBuilder();

            s.Serialize(new JsonTextWriter(new StringWriter(sb)), input, typeof(IFeature));
            return((IFeature)s.Deserialize <IFeature>(new JsonTextReader(new StringReader(sb.ToString()))));
        }
        public virtual string GetGeoJsonCoordinate()
        {
            var wkbReader  = new WKBReader();
            var geometry   = wkbReader.Read(Coord);
            var point      = (Point)geometry;
            var serializer = GeoJsonSerializer.Create();

            using (var stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, point);
                var geoJson = stringWriter.ToString();
                return(JObject.Parse(geoJson)["coordinates"].ToString(Formatting.None));
            };
        }
예제 #29
0
        public void serialize_an_array_of_geometries_should_return_a_json_fragment()
        {
            var sb         = new StringBuilder();
            var writer     = new JsonTextWriter(new StringWriter(sb));
            var serializer = GeoJsonSerializer.Create(new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            }, factory);

            serializer.Serialize(writer, geometries);
            string actual = sb.ToString();

            Console.WriteLine(actual);
            Assert.That(actual, Is.EqualTo(serializedGeometries));
        }
예제 #30
0
 private void loadJsonOptions(MvcNewtonsoftJsonOptions options)
 {
     //options.SerializerSettings.TraceWriter = new memoryTraceWriter();
     options.SerializerSettings.ReferenceLoopHandling          = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
     options.SerializerSettings.MissingMemberHandling          = Newtonsoft.Json.MissingMemberHandling.Ignore;
     options.SerializerSettings.NullValueHandling              = Newtonsoft.Json.NullValueHandling.Ignore;
     options.SerializerSettings.TypeNameHandling               = Newtonsoft.Json.TypeNameHandling.None;
     options.SerializerSettings.TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple;
     options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
     //needed for geojson serializer
     foreach (var converter in GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel(), 4326)).Converters)
     {
         options.SerializerSettings.Converters.Add(converter);
     }
 }