Code Monkey home page Code Monkey logo

geojson's Introduction

BAMCIS GeoJSON

An implementation of GeoJSON written in .NET Core 2.0. The library complies with the requirements of RFC 7946 (https://tools.ietf.org/html/rfc7946). Can be found on nuget https://www.nuget.org/packages/geojson.

Table of Contents

Limitations

The library does not support section 6 of RFC 7946, extending GeoJSON with Foreign Members. You would need to extend the existing Geometries, Feature, and FeatureCollection classes with the additional properties included in the serialized JSON.

Usage

Example 1

Given some GeoJSON data, such as:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [ 102.0, 0.5 ]
  },
  "properties": {
    "prop0": "value0"
  }
}

You can receive the text and deserialize it to a GeoJSON object

GeoJson data = JsonConvert.DeserializeObject<GeoJson>(jsonString);

Once the data is deserialized, you can cast it to its actual type

switch (data.Type)
{
    case GeoJsonType.Feature:
    {
        Feature feature = (Feature)data;
        break;
    }
    ...
}

Example 2

If you know what kind of GeoJSON you're receiving, you can deserialize to it directly:

FeatureCollection col = FeatureCollection.FromJson(data);

And also go back to JSON data:

string json = col.ToJson(Formatting.Indented);

Example 3

Or you can create a GeoJSON object and serialize it:

Position pos1 = new Position(100.0, 0.5);
Position pos2 = new Position(101.0, 1.0);
MultiPoint mp = new MultiPoint(new Position[] {pos1, pos2});
string json = JsonConvert.Serialize(mp);

Example 4

The library also supports conversion of Geometry objects to and from Well-Known Binary (WKB). For example:

{
  "type": "Point",
  "coordinates": [ 2.0, 4.0 ]
}
Point point = new Point(102.0, 0.5);
byte[] wkb = point.ToWkb();
point = Geometry.FromWkb<Point>(wkb);

The binary produced is 0x000000000140000000000000004010000000000000. You can also convert this way.

Point point = new Point(102.0, 0.5);
byte[] wkb = point.ToWkb();
Geometry geo = Point.FromWkb(wkb)
point = (Point)geo;

You can also specify the endianness of the binary encoding (the default is LITTLE).

Point point = new Point(102.0, 0.5);
byte[] wkb = point.ToWkb(Endianness.BIG);
Geometry geo = Point.FromWkb(wkb)
point = (Point)geo;

Finally, you can use the WkbConverter class directly.

Point point = new Point(new Position(2.0, 4.0));
byte[] bytes = WkbConverter.ToBinary(point, Endianness.BIG);
byte[] bytes = HexStringToByteArray("000000000140000000000000004010000000000000");
Point point = WkbConverter.FromBinary<Point>(bytes);

Usage Notes

Each of the 9 GeoJSON types: Feature, FeatureCollection, GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, and Polygon all have convenience methods ToJson() and FromJson() to make serialization and deserialization easy.

There are two additional types that can be used. A LinearRing is a LineString that is connected as the start and end and forms the basis of a polygon. You can also use the abstract Geometry class that encompasses LineString, MultiLineString, MultiPoint, MultiPolygon, Point, and Polygon.

The Feature 'Properties' property implements an IDictionary<string, dynamic> in order to accommodate any type of property structure that may be sent.

Global Configuration

This library provides a global configuration class, GeoJsonConfig. Currently, the config offers a way to ignore the validation of latitude and longitude coordinates. For example, given this input:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [ 200.0, 65000.5 ]
  },
  "properties": {
    "prop0": "value0"
  }
}

We would expect this operation to throw an ArgumentOutOfRangeException due to the coordinate values.

Feature geo = JsonConvert.DeserializeObject<Feature>(content);

To ignore the validation, do this:

GeoJsonConfig.IgnorePositionValidation();
Feature geo = JsonConvert.DeserializeObject<Feature>(content);

Revision History

2.3.1

Fixed the Polygon serde CanConvert method.

2.3.0

Added Well-Known Binary serialization and deserialization support for Geometry objects.

2.2.0

Added an Id property to Feature. Also added a global config object that can be used to ignore validation of coordinate values.

2.1.1

Added validation for latitude and longitude values in Position.

2.1.0

Added a method to remove interior linear rings from a Polygon object.

2.0.2

Fixed bug for MultiLineString with less than 2 coordinates.

2.0.1

Bug fix for NULL geometry JSON token in a Feature, which is allowed by the RFC.

2.0.0

Changed JSON serialized property names to proper camel case by default to be RFC compliant. Added strong-named assembly signing.

1.2.1

Fixed sequence comparison null value handling.

1.2.0

Enabled the use of the bounding box property on all GeoJSON types.

1.1.2

Actually fixed targeting netstandard1.6 instead of v1.6.1.

1.1.1

Fixed targeting of netstandard1.6, dropped JSON.NET to 9.0.1. Added netstandard2.0 and net45 as target frameworks.

1.1.0

Retargeted library to netstandard1.6.

1.0.0

Initial release of the library.

geojson's People

Contributors

cristianst85 avatar dependabot[bot] avatar hakenmt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

geojson's Issues

Error deserializing with NULL Geometry

With: var data = JsonConvert.DeserializeObject<GeoJson>(json);
I get:
'Error reading JObject from JsonReader. Current JsonReader item is not an object: Null. Path 'features[0].geometry', line 12, position 28.'

from this file:

{
    "type": "FeatureCollection",
    "crs": {
        "type": "name",
        "properties": {
            "name": "EPSG:4326"
        }
    },
    "features": [{
            "type": "Feature",
            "id": 1484657,
            "geometry": null,
            "properties": {
...

This file is an export from GIS. I can't tell if the file doesn't meet the GeoJson standard or if the library can't handle a valid case.

Deserialization of Large Files Takes a Long Time and Consumes a Lot of RAM

I have a geojson file containing over 33,000 features in the feature collection. Reading the file in as text consume about 400 MB of RAM, but only takes a second or two. When I deserialize the json though, an additional 4 GB of RAM is consumed, and the operation takes more than 30 seconds. My code:

            var data = File.ReadAllText(dataFile);
            var serializerSettings = new JsonSerializerSettings();
            var zipCodeTabulationAreasGeoJson = JsonConvert.DeserializeObject<GeoJson>(data, serializerSettings);

Maybe I am doing this wrong for my use-case. Is there a better way? Instead of deserializing ALL the features at once, perhaps we could add something that would allow for a lazy-load approach where each feature is deserialized when it is accessed? I know that processing large files will, by definition, require a lot of RAM and time, but I thought this might be a good discussion point.

Deserialized GeoJson has features but no properties (from a groupBy query)

The GeoJSON library is having trouble deserializing this:

{
    "displayFieldName": "",
    "fieldAliases": {
        "MUNICIPALITY": "MUNICIPALITY",
        "mcount": "mcount"
    },
    "fields": [{
            "name": "MUNICIPALITY",
            "type": "esriFieldTypeString",
            "alias": "MUNICIPALITY",
            "length": 100
        }, {
            "name": "mcount",
            "type": "esriFieldTypeInteger",
            "alias": "mcount"
        }
    ],
    "features": [{
            "attributes": {
                "MUNICIPALITY": "Upper Enchanted Twp",
                "mcount": 33
            }
        }, {
            "attributes": {
                "MUNICIPALITY": "Dixmont",
                "mcount": 583
            }
        }
    ]
}

That is a sample of what I get back from a GIS server when I request the result is formatted as GeoJson. In case more context helps, the query I ran was to group by municipality, and count how many features are in each group. I think the GeoJson is valid.
There are no errors deserializing it, but the Features in the FeatureCollection don't have any properties.

string json = {...};
FeatureCollection collection = FeatureCollection.FromJson(json);
var firstMunicipality = collection.Features.First().Properties["MUNICIPALITY"];
// Throw "System.Collections.Generic.KeyNotFoundException"

Am I using it wrong, or is it broken?

[Geo]JSON is case-sensitive, must use `type` instead of `Type`, etc.

GeoJSON produced by the library is invalid, as it uses wrongly-capitalized field names, e.g. "Type":"FeatureCollection" instead of the correct "type":"FeatureCollection".

As JSON (and GeoJSON) is case-sensitive, this is an important difference, meaning the produced GeoJSON does not work elsewhere.

Assemblies are not Strongly Named, hence unusable to me in current form

I tried to reference your NuGet package, but unfortunately (as my C# solution consists of Strongly Named assemblies), all I get at runtime isthe following exception:

System.IO.FileLoadException: 'Could not load file or assembly '[name], Version=#.#.#.#, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)'

Could you please update your package to be strongly named? Or else I see no other option to include some of your source code in my own instead of referencing your NuGet package, which sort of defeats the whole purpose, doesn't it...?

Not able to install on .NET 4.0

Hello, I hope you are good.
I'm having trouble installing your library in our project (using .NET 4.0)

this is what nuGet reports:

Installing 'GeoJSON 1.1.0'. Successfully installed 'GeoJSON 1.1.0'. Adding 'GeoJSON 1.1.0' to CMapServiceLibrary. Uninstalling 'GeoJSON 1.1.0'. Successfully uninstalled 'GeoJSON 1.1.0'. Install failed. Rolling back... Could not install package 'GeoJSON 1.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

let me know if you need more details,
Cheers Matteo

Properties are read only.

In my code, I need to take the return value of a geoJson and (depending on logic for my code) remove any holes from the geo json. My code is as follows:
GeoJson geoJson = this._serializer.deserializeGeoJsonFromString(geojsonGeom); FeatureCollection featureCollection = geoJson as FeatureCollection; Feature[] features = featureCollection.Features.ToArray(); for (int i = 0; i < features.Length; i++) { Feature f = features[i]; switch(f.Geometry.Type) { ... case GeoJsonType.Polygon: default: Polygon p = (Polygon)f.Geometry; p.Coordinates = new LinearRing[] { p.Coordinates.ToArray()[0] }; break; } }
However, when the code tries to compile I get the error p.Coordinates is a read only property. Is there a way to set these objects up so I can manipulate them for my code?

Example 3

Example 3 is very straight forward but I need properties as well as coordinates. Do you have and Example like #3 for Features and FeatureCollections?

Lower dependency version on NewtonSoft.Json

Lower the dependency to minimum required e.g. 10.0.3 can be supported at netstandard 1.0

Otherwise you force dependent libraries/apps to upgrade beyond what they might be using

MultiLineString should support less than two LineStrings?

Hi, as far as I understand it, when the RFC says

For type "MultiLineString", the "coordinates" member is an array of LineString coordinate arrays

that would at least include the situation where there is only one linestring present (possibly zero linestrings?). The code, as it stands, rejects a single linestring with an error.

Null value parsing

Hey, I have tried library, it's awesome, but I have an issue with null value.

I have created my Dto object which has several GeoJson properties:

public class ParkingZoneDto
 {
        [JsonProperty]
        public int Id { get; set; }

        [JsonProperty]
        public string Name { get; set; }

        [JsonProperty]
        public GeoJson GeographyPolygons { get; set; }

        [JsonProperty]
        public GeoJson PinPositions { get; set; }
}

And JsonConvert.DeserializeObject failing when in the response property PinPossitions is null (some times here should be MultiPoint) :

{
    ...,
    "PinPositions": null,
    ...
}

Error is: Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: Null. Path '[0].PinPositions', line 1, position 41. at Newtonsoft.Json.Linq.JObject.Load (Newtonsoft.Json.JsonReader reader,...

If I removed that property from my response string, then deserialization success and PinPositions property in my dto is null. So I hoping that this case should be covered by library: don't try parse null value into GeoJson object.

Am I missing something? Maybe is better workaround than removing properties from content string before desereliazation? thanks in advance.

FeatureCollection: name, totalFeatures, crs

Hi all,

I'm working with GeoJson files whose featureCollection has the following properties:
crs
name
totalFeatures

I don't know if those fields are standard. Nevertheless, "crs" seems important as it declares the format the geoJson was generated with. Example: EPSG:31370, EPSG:4326, etc

featurecollection.crs = { type: 'name', properties: { name: 'urn:ogc:def:crs:EPSG::4326' } }; //EPSG:4326

name: file name
totalFeatures: features length

Do you intend to add those properties to featureCollection any time soon?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.