Struct geojson::FeatureWriter
source · pub struct FeatureWriter<W: Write> { /* private fields */ }
Expand description
Write Features to a FeatureCollection
Implementations§
source§impl<W: Write> FeatureWriter<W>
impl<W: Write> FeatureWriter<W>
sourcepub fn from_writer(writer: W) -> Self
pub fn from_writer(writer: W) -> Self
Create a FeatureWriter from the given writer
.
To append features from your custom structs, use FeatureWriter::serialize
.
To append features from Feature
use FeatureWriter::write_feature
.
sourcepub fn write_feature(&mut self, feature: &Feature) -> Result<()>
pub fn write_feature(&mut self, feature: &Feature) -> Result<()>
Write a crate::Feature
struct to the output stream. If you’d like to
serialize your own custom structs, see FeatureWriter::serialize
instead.
sourcepub fn serialize<S: Serialize>(&mut self, value: &S) -> Result<()>
pub fn serialize<S: Serialize>(&mut self, value: &S) -> Result<()>
Serialize your own custom struct to the features of a FeatureCollection using the
serde
crate.
§Examples
Your struct must implement or derive serde::Serialize
.
If you have enabled the geo-types
feature, which is enabled by default, you can
serialize directly from a useful geometry type.
use geojson::{FeatureWriter, ser::serialize_geometry};
#[derive(serde::Serialize)]
struct MyStruct {
#[serde(serialize_with = "serialize_geometry")]
geometry: geo_types::Point<f64>,
name: String,
age: u64,
}
Then you can serialize the FeatureCollection directly from your type.
let dinagat = MyStruct {
geometry: geo_types::point!(x: 125.6, y: 10.1),
name: "Dinagat Islands".to_string(),
age: 123
};
let neverland = MyStruct {
geometry: geo_types::point!(x: 2.3, y: 4.5),
name: "Neverland".to_string(),
age: 456
};
let mut output: Vec<u8> = vec![];
{
let io_writer = std::io::BufWriter::new(&mut output);
let mut feature_writer = FeatureWriter::from_writer(io_writer);
feature_writer.serialize(&dinagat).unwrap();
feature_writer.serialize(&neverland).unwrap();
}
let expected_output = r#"{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": { "type": "Point", "coordinates": [125.6, 10.1] },
"properties": {
"name": "Dinagat Islands",
"age": 123
}
},
{
"type": "Feature",
"geometry": { "type": "Point", "coordinates": [2.3, 4.5] },
"properties": {
"name": "Neverland",
"age": 456
}
}
]
}"#.as_bytes();
fn assert_eq_json(bytes_1: &[u8], bytes_2: &[u8]) {
// check for semantic equality, discarding any formatting/whitespace differences
let json_1: serde_json::Value = serde_json::from_slice(bytes_1).unwrap();
let json_2: serde_json::Value = serde_json::from_slice(bytes_2).unwrap();
assert_eq!(json_1, json_2);
}
assert_eq_json(expected_output, &output);
If you’re not using geo-types
, you can deserialize to a geojson::Geometry
instead.
use serde::Deserialize;
#[derive(Deserialize)]
struct MyStruct {
geometry: geojson::Geometry,
name: String,
age: u64,
}