GeoJsonConverter

Namespace: GeoJSON.Net
We found 10 examples in language CSharp for this search. You will see 35 fragments of code.
    public static string ToGeoJson(this FeatureCollection featureCollection)
    {
      if (featureCollection == null)
        throw new ArgumentNullException("featureCollection");
      JTokenWriter jtokenWriter = new JTokenWriter();
      FeatureCollection featureCollection1 = featureCollection;
      GeoJsonConverter.Write((JsonWriter) jtokenWriter, (IEnumerable<Feature>) featureCollection1);
      return jtokenWriter.Token.ToString();
    }

    public static string ToGeoJson(this IEnumerable<Feature> featureCollection)
    {
      if (featureCollection == null)
        throw new ArgumentNullException("featureCollection");
      JTokenWriter jtokenWriter = new JTokenWriter();
      IEnumerable<Feature> featureCollection1 = featureCollection;
      GeoJsonConverter.Write((JsonWriter) jtokenWriter, featureCollection1);
      return jtokenWriter.Token.ToString();
    }

    public static FeatureCollection ToFeatureCollection(this string geoJson)
    {
      return GeoJsonConverter.ReadFeatureCollection((JsonReader) new JsonTextReader((TextReader) new StringReader(geoJson)));
    }

    internal static List<Feature> ReadFeatureArray(JsonReader jsonReader)
    {
      List<Feature> featureList = new List<Feature>();
      jsonReader.Read();
      while (jsonReader.TokenType != JsonToken.EndArray)
      {
        Feature feature = GeoJsonConverter.ReadFeature(jsonReader);
        if (feature == null)
          return featureList;
        featureList.Add(feature);
        jsonReader.Read();
      }
      return featureList;
    }

    public static string ToGeoJson(this Feature feature)
    {
      if (feature == null)
        throw new ArgumentNullException("feature");
      JTokenWriter jtokenWriter = new JTokenWriter();
      Feature feature1 = feature;
      GeoJsonConverter.Write((JsonWriter) jtokenWriter, feature1);
      return jtokenWriter.Token.ToString();
    }

    public static Feature ToFeature(this string geoJson)
    {
      return GeoJsonConverter.ReadFeature((JsonReader) new JsonTextReader((TextReader) new StringReader(geoJson)));
    }

        /// <summary>
        /// Generates GeoJson for the given feature collection.
        /// </summary>
        public static string ToGeoJson(this FeatureCollection featureCollection)
        {
            if (featureCollection == null) { throw new ArgumentNullException("featureCollection"); }

            var jsonWriter = new JTokenWriter();
            GeoJsonConverter.Write(jsonWriter, featureCollection);
            return jsonWriter.Token.ToString();
        }

        /// <summary>
        /// Generates GeoJson for the given feature collection.
        /// </summary>
        public static string ToGeoJson(this IEnumerable<Feature> featureCollection)
        {
            if (featureCollection == null) { throw new ArgumentNullException("featureCollection"); }

            var jsonWriter = new JTokenWriter();
            GeoJsonConverter.Write(jsonWriter, featureCollection);
            return jsonWriter.Token.ToString();
        }

        /// <summary>
        /// Reads GeoJson and returns the feature collection.
        /// </summary>
        /// <param name="geoJson"></param>
        /// <returns></returns>
        public static FeatureCollection ToFeatureCollection(this string geoJson)
        {
            var jsonReader = new JsonTextReader(new StringReader(geoJson));
            return GeoJsonConverter.ReadFeatureCollection(jsonReader);
        }

        /// <summary>
        /// Generates GeoJson for the given feature.
        /// </summary>
        /// <param name="feature"></param>
        public static string ToGeoJson(this Feature feature)
        {
            if (feature == null) { throw new ArgumentNullException("feature"); }

            var jsonWriter = new JTokenWriter();
            GeoJsonConverter.Write(jsonWriter, feature);
            return jsonWriter.Token.ToString();
        }

        /// <summary>
        /// Reads GeoJson and returns the feature.
        /// </summary>
        /// <param name="geoJson"></param>
        /// <returns></returns>
        public static Feature ToFeature(this string geoJson)
        {
            var jsonReader = new JsonTextReader(new StringReader(geoJson));
            return GeoJsonConverter.ReadFeature(jsonReader);
        }

        /// <summary>
        /// Generates GeoJson for this geometry.
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        public static string ToGeoJson(this LineairRing geometry)
        {
            if (geometry == null) { throw new ArgumentNullException("geometry"); }

            var jsonWriter = new JTokenWriter();
            GeoJsonConverter.Write(jsonWriter, geometry);
            return jsonWriter.Token.ToString();
        }


        public T GeographyFromGeoJSON<T>(string input)
            where T : class, ISpatial
        {
            var geoJsonConverter = new GeoJsonConverter<T>();
            JsonTextReader reader = new JsonTextReader(new StringReader(input));
            JsonSerializer serializer = new JsonSerializer();
            var result = geoJsonConverter.ReadJson(reader, typeof(T), input, serializer);
            return (T)result;
        }

        [Test]
        public void Grid500KmToGeoJsonTest()
        {
            new GridImportTest().StoreSsb500KmTest();

            var grid = SqlServer.GetGrid(RutenettType.SSB500KM, new Collection<int>(), new Collection<int>(), "", "", 3857, 0);
            var gridJson = GeoJsonConverter.GridToGeoJson(grid, false);
            Assert.True(gridJson.Length > 10000); // 10479
        }

        [Test][Ignore("Runtime > 1 minute")]
        public void Grid1KmToGeoJsonTest()
        {
            new GridImportTest().StoreSsb001KmTest();

            var grid = SqlServer.GetGrid(RutenettType.SSB001KM, new Collection<int>(), new Collection<int>(), "", "", 3857, 0);
            var gridJson = GeoJsonConverter.GridToGeoJson(grid, false);
            Assert.IsNotEmpty(gridJson);
            Assert.AreEqual(152909657, gridJson.Length);
        }


        public override bool CanConvert(Type objectType)
        {
            return typeof(IGeometry).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return _reader.ReadJson(reader, objectType, existingValue, serializer);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            _writer.WriteJson(writer, value, serializer);
        }


        static MongoClient GetClient()
        {
            try
            {
                var client = new MongoClient(TestConnection);
                foreach (var dbNames in client.ListDatabaseNames().ToEnumerable())
                {
                    Log.Debug(fmh => fmh("{0}", dbNames));
                }
                return client;
            }
            catch (Exception ex)
            {
                Log.Debug(fmh => fmh("MongoDB Server not found or running"));
            }
            return null;
        }

        [OneTimeSetUp]
        public void SetUp()
        {
            _client = GetClient();
            if (_client == null)
            {
                try
                {
                    System.Diagnostics.Process.Start(StartMongoDbServerCommand, StartMongoDbServerArguments);
                    Thread.Sleep(2000);
                }
                catch (Exception e)
                {
                    throw new IgnoreException("Failed to start MongoDB Server", e);
                }
                finally
                {
                    _client = GetClient();
                }
            }
            if (_client == null)
                throw new IgnoreException("Creation of MongoClient failed");

            /*
            //var server = _client.Settings.;
            if (server.BuildInfo != null)
            {
                if (server.BuildInfo.Version < new Version(2, 4))
                    throw new IgnoreException("MongoDB server must have at least version 2.4");
            }
             */
            if (_client.GetDatabase(TestDatabase) != null)
                _client.DropDatabase(TestDatabase);

            GeoAPI.GeometryServiceProvider.Instance = NetTopologySuite.NtsGeometryServices.Instance;
            CreatePoIDatabase(_client);
        }

        private static void CreatePoIDatabase(IMongoClient client)
        {
            var db = client.GetDatabase(TestDatabase);
            try
            {
                db.CreateCollection("Items");
            }
            catch (Exception e)
            {
                throw new IgnoreException("Faild to create collection items", e);
            }

            //Assign the converter
            PoI.Converter = GeoJsonConverter.Converter2D;
            
            var col = db.GetCollection<PoI>("Items");
            var factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4326);
            for (uint oid = 1; oid <= 1000; oid++)
            {
                col.InsertOne(RndPoi(ref oid, factory));
            }
            


        }

        [Test]
        public void Test1()
        {
            MongoDbBusinessObjectSource<PoI, GeoJson2DCoordinates> repo = null;
            Assert.DoesNotThrow( () => repo =
                new PoIRepository(
                    GeoJsonConverter.Converter2D,
                    TestConnection, TestDatabase, TestCollection));

            Assert.IsNotNull(repo);
            Assert.AreEqual(1000, repo.Count);
        }

        [Test]
        public void Test2()
        {
            MongoDbBusinessObjectSource<PoI, GeoJson2DCoordinates> repo = null;
            Assert.DoesNotThrow(() => repo =
                new PoIRepository(
                    GeoJsonConverter.Converter2D,
                    TestConnection, TestDatabase, TestCollection));

            Assert.IsNotNull(repo);
            var extent = repo.GetExtents();
            extent = extent.Grow(-0.2*extent.Width, -0.2*extent.Height);
            Assert.Less(repo.Select(extent).Count(), 1000);
        }

        [Test]
        public void TestWithProvider()
        {
            MongoDbBusinessObjectSource<PoI, GeoJson2DCoordinates> repo = null;
            Assert.DoesNotThrow(() => repo =
                new PoIRepository(
                    GeoJsonConverter.Converter2D,
                    TestConnection, TestDatabase, TestCollection));

            var p = new BusinessObjectProvider<PoI>(TestCollection, repo);
            var vl = new VectorLayer(p.ConnectionID, p);

            var bl = new BusinessObjectLayer<PoI>(repo);

            var m = new Map();
            m.Layers.Add(vl);
            m.Layers.Add(bl);
            m.ZoomToExtents();
            m.GetMap().Save("MongoDB.PoI.png", ImageFormat.Png);
            m.Dispose();
        }


		public virtual bool TryConvert(object value, out string result)
		{
			var s = value as string;
			if (s != null)
			{
				result = s;
				return true;
			}

			var jValue = value as RavenJValue;
			if (jValue != null && jValue.Type == JTokenType.String)
			{
				result = (string)jValue.Value;
				return true;
			}

			var enumerable = value as IEnumerable;
			if (enumerable != null)
			{
				var list = enumerable.Cast<object>().ToList();
				if (list.Count > 1 && list.All(IsNumber))
				{
					result = MakePoint(GetDouble(list[0]), GetDouble(list[1]));
					return true;
				}

				var keyValues = list.OfType<KeyValuePair<string, object>>()
				                    .Where(x => IsNumber(x.Value))
				                    .ToDictionary(x => x.Key, x => x.Value);

				if (keyValues.Count == 0)
				{
					keyValues = list.OfType<KeyValuePair<string, RavenJToken>>()
									.Where(x => IsNumber(x.Value))
									.ToDictionary(x => x.Key, x => (object) x.Value);
				}

				if (keyValues.Count > 1)
				{
					var x1 = keyValues.Select(x => x.Key).FirstOrDefault(c => RegexX.IsMatch(c));
					var y1 = keyValues.Select(x => x.Key).FirstOrDefault(c => RegexY.IsMatch(c));

					if (x1 != null && y1 != null)
					{
						result = MakePoint(GetDouble(keyValues[x1]), GetDouble(keyValues[y1]));
						return true;
					}
				}
			}

			var djObj = value as IDynamicJsonObject;
			var jObj = djObj != null ? djObj.Inner : value as RavenJObject;

			if (jObj != null && GeoJsonConverter.TryConvert(jObj, out result))
				return true;

			result = default(string);
			return false;
		}

		private bool IsNumber(object obj)
		{
			var rValue = obj as RavenJValue;
			return obj is double
			       || obj is float
			       || obj is int
			       || obj is long
			       || obj is short
			       || rValue != null && (rValue.Type == JTokenType.Float || rValue.Type == JTokenType.Integer);
		}

		private double GetDouble(object obj)
		{
			if (obj is double || obj is float || obj is int || obj is long || obj is short)
				return Convert.ToDouble(obj);

			var rValue = obj as RavenJValue;
			if (rValue != null && (rValue.Type == JTokenType.Float || rValue.Type == JTokenType.Integer))
				return Convert.ToDouble(rValue.Value);

			return 0d;
		}

		protected string MakePoint(double x, double y)
		{
			return string.Format(CultureInfo.InvariantCulture, "POINT ({0} {1})", x, y);
		}

		protected string MakeCircle(double x, double y, double radius)
		{
			return string.Format(CultureInfo.InvariantCulture, "Circle({0} {1} d={2})", x, y, radius);
		}

        /// <summary>
        /// Return a list of JsonConverters for GeoJson support.
        /// <para>Default System.Text.Json:</para>
        /// <list type="bullet">
        /// <item>
        /// JsonStringEnumConverter(JsonNamingPolicy.CamelCase, true)
        /// </item> 
        /// <para>GeoJson:</para>
        /// <item>
        /// FeatureCollectionConverter
        /// </item>
        /// <item>
        /// FeatureConverter
        /// </item>
        /// <item>
        /// FeatureIdConverter
        /// </item>
        /// <item>
        /// GeoJsonConverter
        /// </item>
        /// <item>
        /// GeometryCollectionConverter
        /// </item>
        /// <item>
        /// GeometryConverter
        /// </item>
        /// <item>
        /// LineStringConverter
        /// </item>
        /// <item>
        /// MultiLineStringConverter
        /// </item>
        /// <item>
        /// MultiPointConverter
        /// </item>
        /// <item>
        /// MultiPolygonConverter
        /// </item>
        /// <item>
        /// PointConverter
        /// </item>
        /// <item>
        /// PolygonConverter
        /// </item>
        /// <item>
        /// PositionConverter
        /// </item>
        /// </list>
        /// </summary>
        public static IEnumerable<JsonConverter> Converters()
        {
            return new List<JsonConverter>
            {
                // default System.Text.Json converter for enums
                new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, true),
                new FeatureCollectionConverter(),
                new FeatureConverter(),
                new FeatureIdConverter(),
                new GeoJsonConverter(),
                new GeometryCollectionConverter(),
                new GeometryConverter(),
                new LineStringConverter(),
                new MultiLineStringConverter(),
                new MultiPointConverter(),
                new MultiPolygonConverter(),
                new PointConverter(),
                new PolygonConverter(),
                new PositionConverter()
            };
        }

        /// <summary>
        /// Extension method to add the converters to the <see cref="JsonSerializerOptions"/>
        /// </summary>
        /// <param name="options">The <see cref="JsonSerializerOptions"/> to add the converter to</param>
        public static void AddConverters(this JsonSerializerOptions options)
        {
            foreach (var converter in Converters())
            {
                options.Converters.Add(converter);
            }
        }



        protected override FilterDefinition<PoI> BuildEnvelopeQuery(Envelope box)
        {
            //return Query<PoI>.GeoIntersects(t => t.BsonGeometry, Converter.ToPolygon(box));
            return Builders<PoI>.Filter.GeoWithinBox(t => t.BsonGeometry, box.MinX, box.MinY, box.MaxX, box.MaxY);        
        }


		public override bool CanConvert(Type objectType)
		{
			return typeof(IGeometry).IsAssignableFrom(objectType)
				|| objectType == typeof(Feature)
				|| objectType == typeof(FeatureCollection)
				|| objectType == typeof(Route)
				|| objectType == typeof(Track);
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			return _reader.ReadJson(reader, objectType, existingValue, serializer);
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			_writer.WriteJson(writer, value, serializer);
		}

GeoJSON.Net.Converters.GeoJsonConverter : JsonConverter

Constructors :

public GeoJsonConverter()

Methods :

public Boolean CanConvert(Type objectType = )
public Object ReadJson(JsonReader reader = , Type objectType = , Object existingValue = , JsonSerializer serializer = )
public Void WriteJson(JsonWriter writer = , Object value = , JsonSerializer serializer = )
public Boolean get_CanRead()
public Boolean get_CanWrite()
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()