Expand description
Build your struct from GeoJSON using serde
To build instances of your struct from a GeoJSON String or reader, your type must
implement or derive serde::Deserialize
:
ⓘ
#[derive(serde::Deserialize)]
struct MyStruct {
...
}
Your type must have a field called geometry
and it must be deserialize_with
deserialize_geometry
:
ⓘ
#[derive(serde::Deserialize)]
struct MyStruct {
#[serde(deserialize_with = "geojson::de::deserialize_geometry")]
geometry: geo_types::Point<f64>,
...
}
All fields in your struct other than geometry
will be deserialized from the properties
of the
GeoJSON Feature.
§Examples
use serde::Deserialize;
use geojson::de::deserialize_geometry;
#[derive(Deserialize)]
struct MyStruct {
// Deserialize from GeoJSON, rather than expecting the type's default serialization
#[serde(deserialize_with = "deserialize_geometry")]
geometry: geo_types::Point<f64>,
name: String,
population: u64
}
let input_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
}
}
]
}
).to_string();
let my_structs: Vec<MyStruct> = geojson::de::deserialize_feature_collection_str_to_vec(&input_geojson).unwrap();
assert_eq!("Downtown", my_structs[0].name);
assert_eq!(11.1, my_structs[0].geometry.x());
assert_eq!("Uptown", my_structs[1].name);
assert_eq!(33.3, my_structs[1].geometry.x());
§Reading and Writing GeoJSON
This module is only concerned with reading in GeoJSON. If you’d also like to write GeoJSON
output, you’ll want to combine this with the functionality from the crate::ser
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§
- deserialize_
feature_ collection - Deserialize a GeoJSON FeatureCollection into your custom structs.
- deserialize_
feature_ collection_ str_ to_ vec - Build a
Vec
of structs from a GeoJson&str
. - deserialize_
feature_ collection_ to_ vec - Build a
Vec
of structs from a GeoJson reader. - deserialize_
features_ from_ feature_ collection - Deserialize a GeoJSON FeatureCollection into
Feature
structs. - deserialize_
geometry serde::deserialize_with
helper to deserialize a GeoJSON Geometry into another type, like ageo_types
Geometry.- deserialize_
optional_ geometry serde::deserialize_with
helper to deserialize an optional GeoJSON Geometry into another type, like an optionalgeo_types
Geometry.- deserialize_
single_ feature - Deserialize a single GeoJSON Feature into your custom struct.
- from_
feature - Interpret a
Feature
as an instance of typeT
.