Module geojson::ser

source ·
Expand description

Write your struct to GeoJSON using serde

To output your struct to GeoJSON, either as a String, bytes, or to a file, your type must implement or derive serde::Serialize:

#[derive(serde::Serialize)]
struct MyStruct {
    ...
}

Your type must have a field called geometry and it must be serialized_with serialize_geometry:

#[derive(serde::Serialize)]
struct MyStruct {
   #[serde(serialize_with = "geojson::ser::serialize_geometry")]
   geometry: geo_types::Point<f64>,
   ...
}

All fields in your struct other than geometry will be serialized as properties of the GeoJSON Feature.

§Examples

use serde::Serialize;
use geojson::ser::serialize_geometry;

#[derive(Serialize)]
struct MyStruct {
    // Serialize as geojson, rather than using the type's default serialization
    #[serde(serialize_with = "serialize_geometry")]
    geometry: geo_types::Point<f64>,
    name: String,
    population: u64
}

let my_structs = vec![
    MyStruct {
        geometry: geo_types::Point::new(11.1, 22.2),
        name: "Downtown".to_string(),
        population: 123
    },
    MyStruct {
        geometry: geo_types::Point::new(33.3, 44.4),
        name: "Uptown".to_string(),
        population: 456
    }
];

let output_geojson = geojson::ser::to_feature_collection_string(&my_structs).unwrap();

let expected_geojson = serde_json::json!(
    {
        "type":"FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": { "coordinates": [11.1,22.2], "type": "Point" },
                "properties": {
                    "name": "Downtown",
                    "population": 123
                }
            },
            {
                "type": "Feature",
                "geometry": { "coordinates": [33.3, 44.4], "type": "Point" },
                "properties": {
                    "name": "Uptown",
                    "population": 456
                }
            }
        ]
    }
);

§Reading and Writing GeoJSON

This module is only concerned with Writing out GeoJSON. If you’d also like to reading GeoJSON, you’ll want to combine this with the functionality from the crate::de module:

#[derive(serde::Serialize, serde::Deserialize)]
struct MyStruct {
    // Serialize as geojson, rather than using the type's default serialization
    #[serde(serialize_with = "serialize_geometry", deserialize_with = "deserialize_geometry")]
    geometry: geo_types::Point<f64>,
    ...
}

Functions§