Esempio n. 1
0
        public void GeoJsonWriterWriteAnyObjectTest()
        {
            AttributesTable attributes = new AttributesTable();
            DateTime        Date       = new DateTime(2012, 8, 8).Date;

            JsonSerializer g  = GeoJsonSerializer.CreateDefault();
            StringBuilder  sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
                g.Serialize(sw, Date);
            string expectedDateString = sb.ToString();

            string expectedResult = "{\"featureCollection\":{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}},\"Date\":" + expectedDateString + "}";

            attributes.Add("test1", "value1");
            IFeature feature = new Feature(new Point(23, 56), attributes);

            FeatureCollection featureCollection = new FeatureCollection(new Collection <IFeature> {
                feature
            })
            {
                CRS = new NamedCRS("name1")
            };
            var gjw = new GeoJsonWriter();

            gjw.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            string actual = gjw.Write(new { featureCollection, Date = Date });

            Assert.AreEqual(expectedResult, actual);
        }
        public void deserialize_geojson_from_osm()
        {
            const string resourceName = "NetTopologySuite.IO.GeoJSON.Test.World_AL6.GeoJson";
            var          assembly     = Assembly.GetExecutingAssembly();

            using (var stream = assembly.GetManifestResourceStream(resourceName))
            {
                Assert.IsNotNull(stream);
                {
                    var serializer = GeoJsonSerializer.CreateDefault();
                    using (var reader = new StreamReader(stream))
                        using (var textReader = new JsonTextReader(reader))
                        {
                            var collection = serializer.Deserialize <FeatureCollection>(textReader);
                            Assert.IsNotNull(collection);
                            Assert.AreEqual(4, collection.Count);

                            foreach (var feature in collection.Features)
                            {
                                Assert.IsNotNull(feature.Geometry);
                                Assert.IsNull(feature.BoundingBox);
                                var attributes = feature.Attributes;
                                Assert.IsNotNull(attributes);
                                var names = attributes.GetNames();
                                foreach (var name in names)
                                {
                                    Console.WriteLine("{0}: {1}", name, attributes[name]);
                                }
                            }
                        }
                }
            }
        }
Esempio n. 3
0
        public Geometry Convert(string sourceMember, ResolutionContext context)
        {
            var serializer = GeoJsonSerializer.CreateDefault();
            var feature    = (Feature)serializer.Deserialize(new StringReader(sourceMember), typeof(Feature));

            return(feature.Geometry);
        }
Esempio n. 4
0
        static void ReadTest1Shp(string shpPath)
        {
            IFeatureSet fs = FeatureSet.Open(shpPath);

            var ntsFec = fs.ToNtsFeatureCollection();

            var newShpPath = Path.Combine(
                Path.GetDirectoryName(shpPath),
                Path.GetFileNameWithoutExtension(shpPath) + "_new.shp");

            var newFs = ntsFec.ToCsFeatureSet();

            newFs.Save(newShpPath);



            var sb         = new StringBuilder();
            var writer     = new StringWriter(sb);
            var serializer = GeoJsonSerializer.CreateDefault();

            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.Serialize(writer, ntsFec);
            writer.Flush();


            Console.WriteLine(writer.ToString());
            writer.Dispose();
            Console.WriteLine();
        }
        public void TestIssue88WithFlatProperties()
        {
            string expectedJson = @"
{
	""id"" : ""00000000-0000-0000-0000-000000000000"",
	""type"" : ""Feature"",
	""geometry"" : null,
	""properties"" : {
		""yesNo 1"" : false,
		""date 1"" : ""2016-02-16T00:00:00""
	},	
	""collection_userinfo"" : ""()"",
	""collection_timestamp"" : ""2016-02-25T14:38:01.9087672"",
	""collection_todoid"" : """",
	""collection_templateid"" : ""nj7Glv-AqV0"",
	""collection_layerid"" : ""nj7Glv-AqV0""	
}
";

            JsonSerializer serializer = GeoJsonSerializer.CreateDefault(new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            Feature feat = null;

            Assert.DoesNotThrow(() =>
            {
                using (JsonReader reader = new JsonTextReader(new StringReader(expectedJson)))
                    feat = serializer.Deserialize <Feature>(reader);
            });

            Assert.IsNotNull(feat);
            Assert.IsNull(feat.Geometry);
        }
Esempio n. 6
0
        public void TestCoordinateDeserialize()
        {
            string         json = "{coordinates:[1.0, 1.0]}";
            JsonSerializer s    = GeoJsonSerializer.CreateDefault();
            Coordinate     c    = s.Deserialize <Coordinate>(new JsonTextReader(new StringReader(json)));

            Console.WriteLine(c.ToString());
        }
Esempio n. 7
0
        public void GeoJsonDeserializePolygonTest()
        {
            var serializer = GeoJsonSerializer.CreateDefault();

            const string s    = "{\"type\": \"Polygon\",\"coordinates\": [[[-180,-67.8710140098964],[-180,87.270282879440586],[180,87.270282879440586],[180,-67.8710140098964],[-180,-67.8710140098964]]],\"rect\": {\"min\": [-180,-67.8710140098964],\"max\": [180,87.270282879440586]}}";
            var          poly = serializer.Deserialize <Polygon>(JObject.Parse(s).CreateReader());

            Assert.IsNotNull(poly);
        }
Esempio n. 8
0
        public void feature_collection_is_serialized_as_geojson_when_type_is_placed_as_last_property()
        {
            const string data       = @"{ ""features"": [], ""type"": ""FeatureCollection"" }";
            var          serializer = GeoJsonSerializer.CreateDefault();
            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));
        }
Esempio n. 9
0
        public void TestCoordinateSerialize()
        {
            Coordinate     coordinate = new Coordinate(1, 1);
            JsonSerializer g          = GeoJsonSerializer.CreateDefault();
            StringBuilder  sb         = new StringBuilder();

            g.Serialize(new JsonTextWriter(new StringWriter(sb)), coordinate);

            Console.WriteLine(sb.ToString());
        }
Esempio n. 10
0
        public void GeoJsonSerializerGeometryTest()
        {
            var sb         = new StringBuilder();
            var writer     = new StringWriter(sb);
            var serializer = GeoJsonSerializer.CreateDefault();

            serializer.Serialize(writer, new Point(23, 56));
            writer.Flush();
            Assert.AreEqual("{\"type\":\"Point\",\"coordinates\":[23.0,56.0]}", sb.ToString());
        }
Esempio n. 11
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.CreateDefault();
         serializer.Serialize(jsonWriter, featureCollection);
         jsonWriter.Flush();
         return(outputStream.ToArray());
     }
 }
Esempio n. 12
0
 /// <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.CreateDefault();
         using (var streamReader = new StreamReader(stream))
             using (var jsonTextReader = new JsonTextReader(streamReader))
             {
                 return(serializer.Deserialize <FeatureCollection>(jsonTextReader));
             }
     }
 }
Esempio n. 13
0
        private string Serialize(IGeometry geo)
        {
            StringBuilder  sb         = new StringBuilder();
            StringWriter   writer     = new StringWriter(sb);
            JsonSerializer serializer = GeoJsonSerializer.CreateDefault();

            serializer.NullValueHandling = NullValueHandling.Ignore;

            serializer.Serialize(writer, geo);

            return(sb.ToString());
        }
Esempio n. 14
0
        public void PerformGeometryTest(IGeometry geom)
        {
            JsonSerializer s  = GeoJsonSerializer.CreateDefault();
            StringBuilder  sb = new StringBuilder();

            s.Serialize(new JsonTextWriter(new StringWriter(sb)), geom);
            string result = sb.ToString();

            Console.WriteLine(result);

            Deserialize(result, geom);
        }
Esempio n. 15
0
        public void GeoJsonSerializerAttributesTest()
        {
            var sb         = new StringBuilder();
            var writer     = new StringWriter(sb);
            var attributes = new Dictionary <string, object>();

            attributes.Add("test1", "value1");
            var serializer = GeoJsonSerializer.CreateDefault();

            serializer.Serialize(writer, attributes);
            writer.Flush();
            Assert.AreEqual("{\"test1\":\"value1\"}", sb.ToString());
        }
        public void GeoJsonSerializerAttributesTest()
        {
            StringBuilder   sb         = new StringBuilder();
            StringWriter    writer     = new StringWriter(sb);
            AttributesTable attributes = new AttributesTable();

            attributes.Add("test1", "value1");
            JsonSerializer serializer = GeoJsonSerializer.CreateDefault();

            serializer.Serialize(writer, attributes);
            writer.Flush();
            Assert.AreEqual("{\"test1\":\"value1\"}", sb.ToString());
        }
Esempio n. 17
0
        public Pdv(IPdvRequest request)
        {
            var gjs = GeoJsonSerializer.CreateDefault();

            this.Id                = 0;
            this.TradingName       = request.TradingName;
            this.OwnerName         = request.OwnerName;
            this.Document          = request.Document;
            this.CoverageArea      = gjs.Deserialize <MultiPolygon>(new JsonTextReader(new StringReader(request.CoverageArea)));
            this.CoverageArea.SRID = 4326;
            this.Address           = gjs.Deserialize <Point>(new JsonTextReader(new StringReader(request.Address)));
            this.Address.SRID      = 4326;
        }
Esempio n. 18
0
        public void TestCoordinatesSerialize()
        {
            Coordinate[] coordinates = new Coordinate[4];
            for (int i = 0; i < coordinates.Length; i++)
            {
                coordinates[i] = new Coordinate(i, i, i);
            }
            StringBuilder  sb = new StringBuilder();
            JsonSerializer g  = GeoJsonSerializer.CreateDefault();

            g.Serialize(new JsonTextWriter(new StringWriter(sb)), coordinates);

            Console.WriteLine(sb.ToString());
        }
Esempio n. 19
0
        public void GeoJsonSerializerFeatureTest()
        {
            var sb         = new StringBuilder();
            var writer     = new StringWriter(sb);
            var attributes = new AttributesTable();

            attributes.Add("test1", "value1");
            var feature    = new Feature(new Point(23, 56), attributes);
            var serializer = GeoJsonSerializer.CreateDefault();

            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.Serialize(writer, feature);
            writer.Flush();
            Assert.AreEqual("{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}", sb.ToString());
        }
Esempio n. 20
0
        public static string ToGeoJson(Geometry input)
        {
            //AttributesTable attributes = new AttributesTable();
            //attributes.Add("test1", "value1");
            //IFeature feature = new Feature(input, attributes);
            //FeatureCollection featureCollection = new FeatureCollection(new Collection<IFeature> { feature })
            //{ CRS = new NamedCRS("name1") };
            StringBuilder  sb         = new StringBuilder();
            StringWriter   writer     = new StringWriter(sb);
            JsonSerializer serializer = GeoJsonSerializer.CreateDefault();

            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.Serialize(writer, input);
            writer.Flush();

            return(sb.ToString());
        }
Esempio n. 21
0
        private static void Deserialize(string result, IGeometry geom)
        {
            JsonSerializer s = GeoJsonSerializer.CreateDefault();
            JsonTextReader r = new JsonTextReader(new StringReader(result));

            IGeometry des;

            if (geom is IPoint)
            {
                des = s.Deserialize <Point>(r);
            }
            else if (geom is ILineString)
            {
                des = s.Deserialize <LineString>(r);
            }
            else if (geom is IPolygon)
            {
                des = s.Deserialize <Polygon>(r);
            }
            else if (geom is IMultiPoint)
            {
                des = s.Deserialize <MultiPoint>(r);
            }
            else if (geom is IMultiLineString)
            {
                des = s.Deserialize <MultiLineString>(r);
            }
            else if (geom is IMultiPolygon)
            {
                des = s.Deserialize <MultiPolygon>(r);
            }
            else if (geom is IGeometryCollection)
            {
                des = s.Deserialize <GeometryCollection>(r);
            }
            else
            {
                throw new Exception();
            }

            Console.WriteLine(des.AsText());
            Assert.IsTrue(des.EqualsExact(geom));
        }
Esempio n. 22
0
        public void TestFactoryMethods()
        {
            var settings = new JsonSerializerSettings();
            var factory  = new GeometryFactory(new PrecisionModel(10000), 4326);

            Assert.That(() => GeoJsonSerializer.CreateDefault(), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.CreateDefault(settings), Throws.Nothing);

            Assert.That(() => GeoJsonSerializer.Create(factory), Throws.Nothing);

            Assert.That(() => GeoJsonSerializer.Create(factory, 1), Throws.ArgumentException);
            Assert.That(() => GeoJsonSerializer.Create(factory, 2), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.Create(factory, 3), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.Create(factory, 4), Throws.ArgumentException);
            Assert.That(() => GeoJsonSerializer.Create(settings, factory), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.Create(settings, factory, 1), Throws.ArgumentException);
            Assert.That(() => GeoJsonSerializer.Create(settings, factory, 2), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.Create(settings, factory, 3), Throws.Nothing);
            Assert.That(() => GeoJsonSerializer.Create(settings, factory, 4), Throws.ArgumentException);
        }
Esempio n. 23
0
        protected override IGeometry Read(byte[] b)
        {
            string json;

            using (var ms = new MemoryStream(b))
            {
                using (var r = new StreamReader(ms))
                    json = r.ReadToEnd();
            }

            var gjs = GeoJsonSerializer.CreateDefault();

            var j = (JObject)gjs.Deserialize(new JsonTextReader(new StringReader(json)));

            switch (j.Value <string>("type"))
            {
            case "Point":
                return(gjs.Deserialize <Point>(new JsonTextReader(new StringReader(json))));

            case "LineString":
                return(gjs.Deserialize <LineString>(new JsonTextReader(new StringReader(json))));

            case "Polygon":
                return(gjs.Deserialize <Polygon>(new JsonTextReader(new StringReader(json))));

            case "MultiPoint":
                return(gjs.Deserialize <MultiPoint>(new JsonTextReader(new StringReader(json))));

            case "MultiLineString":
                return(gjs.Deserialize <MultiLineString>(new JsonTextReader(new StringReader(json))));

            case "MultiPolygon":
                return(gjs.Deserialize <MultiPolygon>(new JsonTextReader(new StringReader(json))));

            case "GeometryCollection":
                return(gjs.Deserialize <GeometryCollection>(new JsonTextReader(new StringReader(json))));

            default:
                throw new InvalidOperationException();
            }
        }
        public void GeoJsonSerializerFeatureCollectionTest()
        {
            StringBuilder   sb         = new StringBuilder();
            StringWriter    writer     = new StringWriter(sb);
            AttributesTable attributes = new AttributesTable();

            attributes.Add("test1", "value1");
            IFeature          feature           = new Feature(new Point(23, 56), attributes);
            FeatureCollection featureCollection = new FeatureCollection(new Collection <IFeature> {
                feature
            })
            {
                CRS = new NamedCRS("name1")
            };
            JsonSerializer serializer = GeoJsonSerializer.CreateDefault();

            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.Serialize(writer, featureCollection);
            writer.Flush();
            Assert.AreEqual("{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[23.0,56.0]},\"properties\":{\"test1\":\"value1\"}}],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"name1\"}}}", sb.ToString());
        }
Esempio n. 25
0
        public void TestIssue88WithoutAdditionalProperties()
        {
            const string expectedJson = @"
{
	""id"" : ""00000000-0000-0000-0000-000000000000"",
	""type"" : ""Feature"",
	""geometry"" : null,
	""properties"" : {
		""yesNo 1"" : false,
		""date 1"" : ""2016-02-16T00:00:00""
	}
}
";

            var     serializer = GeoJsonSerializer.CreateDefault();
            Feature feat       = null;

            Assert.That(() =>
            {
                using (JsonReader reader = new JsonTextReader(new StringReader(expectedJson)))
                {
                    feat = serializer.Deserialize <Feature>(reader);
                }
            }, Throws.Nothing);

            Assert.That(feat, Is.Not.Null);
            Assert.That(feat.Attributes.TryGetId(out object id));
            Assert.That(id, Is.EqualTo("00000000-0000-0000-0000-000000000000"));
            Assert.That(feat.Geometry, Is.Null);

            var attributes = feat.Attributes;

            Assert.That(attributes, Is.Not.Null);
            Assert.That(attributes.Count, Is.EqualTo(3));
            Assert.That(attributes.Exists("yesNo 1"));
            Assert.That(attributes["yesNo 1"], Is.False);
            Assert.That(attributes.Exists("date 1"));
            Assert.That(attributes["date 1"], Is.EqualTo(DateTime.Parse("2016-02-16T00:00:00", CultureInfo.InvariantCulture)));
        }
Esempio n. 26
0
        public void TestDeserializeObjectInsideProperties()
        {
            var f        = NtsGeometryServices.Instance.CreateGeometryFactory(4326);
            var p        = f.CreatePoint(new CoordinateZ(10, 10, 1));
            var featureS = new Feature(p, new AttributesTable(new[] {
                new KeyValuePair <string, object>("data", new MyClass {
                    ValueString = "Hello", ValueInt32 = 17, ValueDouble = Math.PI
                }),
            }));

            var js = GeoJsonSerializer.CreateDefault();

            js.TypeNameHandling = TypeNameHandling.Objects;
            var ms       = GeoJsonSerializerTest.Serialize(js, featureS);
            var featureD = (Feature)GeoJsonSerializerTest.Deserialize(js, ms, typeof(Feature));

            Assert.That(featureD.Attributes["data"], Is.InstanceOf <MyClass>());
            var mc = (MyClass)featureD.Attributes["data"];

            Assert.That(mc.ValueString, Is.EqualTo("Hello"));
            Assert.That(mc.ValueInt32, Is.EqualTo(17));
            Assert.That(mc.ValueDouble, Is.EqualTo(Math.PI));
        }
Esempio n. 27
0
        public void TestIssue88()
        {
            const string expectedJson = @"
{
	""id"" : ""00000000-0000-0000-0000-000000000000"",
	""type"" : ""Feature"",
	""geometry"" : null,
	""properties"" : {
		""yesNo 1"" : false,
		""date 1"" : ""2016-02-16T00:00:00""
	},
	""metadata"" : {
		""collection_userinfo"" : ""()"",
		""collection_timestamp"" : ""2016-02-25T14:38:01.9087672"",
		""collection_todoid"" : """",
		""collection_templateid"" : ""nj7Glv-AqV0"",
		""collection_layerid"" : ""nj7Glv-AqV0""
	}
}
";

            var serializer = GeoJsonSerializer.CreateDefault(new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            Feature feat = null;

            Assert.That(() =>
            {
                using (JsonReader reader = new JsonTextReader(new StringReader(expectedJson)))
                {
                    feat = serializer.Deserialize <Feature>(reader);
                }
            }, Throws.Nothing);

            Assert.That(feat, Is.Not.Null);
            Assert.That(feat.Geometry, Is.Null);
        }
        public void TestIssue88WithoutAdditionalProperties()
        {
            string expectedJson = @"
{
	""id"" : ""00000000-0000-0000-0000-000000000000"",
	""type"" : ""Feature"",
	""geometry"" : null,
	""properties"" : {
		""yesNo 1"" : false,
		""date 1"" : ""2016-02-16T00:00:00""
	}
}
";

            JsonSerializer serializer = GeoJsonSerializer.CreateDefault();
            Feature        feat       = null;

            Assert.DoesNotThrow(() =>
            {
                using (JsonReader reader = new JsonTextReader(new StringReader(expectedJson)))
                    feat = serializer.Deserialize <Feature>(reader);
            });

            Assert.IsNotNull(feat);
            Assert.IsTrue(FeatureExtensions.HasID(feat));
            Assert.AreEqual("00000000-0000-0000-0000-000000000000", FeatureExtensions.ID(feat));
            IGeometry geometry = feat.Geometry;

            Assert.IsNull(geometry);
            IAttributesTable attributes = feat.Attributes;

            Assert.IsNotNull(attributes);
            Assert.AreEqual(3, attributes.Count);
            Assert.AreEqual(FeatureExtensions.ID(feat), attributes["id"]);
            Assert.AreEqual(false, attributes["yesNo 1"]);
            Assert.AreEqual(DateTime.Parse("2016-02-16T00:00:00", CultureInfo.InvariantCulture), attributes["date 1"]);
        }
        public void TestDefaultSridOfDeserializedGeometryIs4326()
        {
            const string geojson =
                @"{
  ""id"": ""featureID"",
  ""type"": ""Feature"",
  ""geometry"": {
    ""type"": ""Point"",
    ""coordinates"": [42, 42]
  }
  // no ""properties"" here!!
 }";

            Feature f = null;

            Assert.That(() => f = new GeoJsonReader().Read <Feature>(geojson), Throws.Nothing);
            Assert.That(f, Is.Not.Null);
            Assert.That(f.Geometry, Is.Not.Null);
            Assert.That(f.Geometry.SRID, Is.EqualTo(4326));

            f = null;
            var gf = new GeometryFactory(new PrecisionModel(), 10010);

            Assert.That(() => f = new GeoJsonReader(gf, new JsonSerializerSettings()).Read <Feature>(geojson),
                        Throws.Nothing);
            Assert.That(f, Is.Not.Null);
            Assert.That(f.Geometry, Is.Not.Null);
            Assert.That(f.Geometry.SRID, Is.EqualTo(10010));

            f = null;
            var s = GeoJsonSerializer.CreateDefault();

            f = s.Deserialize <Feature>(new JsonTextReader(new StringReader(geojson)));
            Assert.That(f, Is.Not.Null);
            Assert.That(f.Geometry, Is.Not.Null);
            Assert.That(f.Geometry.SRID, Is.EqualTo(4326));
        }
Esempio n. 30
0
 public void GeoJsonDeserializeIssue176()
 {
     TestIssue176(GeoJsonSerializer.CreateDefault());
 }