Skip to content

Commit

Permalink
Added convenience wrappers for stringifying geojson
Browse files Browse the repository at this point in the history
  • Loading branch information
jeresuikkila authored and michaelkirk committed Jul 14, 2023
1 parent 439c384 commit 5d033b6
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
* Modified conversion from JSON to reject zero- and one-dimensional positions.
* PR: <https://github.com/georust/geojson/pull/225>

* Added `geojson::{to_string, to_string_pretty}` as convenience wrappers around the same `serde_json` methods.

## 0.24.0

* Added `geojson::{ser, de}` helpers to convert your custom struct to and from GeoJSON.
Expand Down
18 changes: 18 additions & 0 deletions examples/geojson_to_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use std::error::Error;
use std::fs::File;
use std::io::BufReader;

use geojson::{Feature, GeoJson};

fn main() -> Result<(), Box<dyn Error>> {
let file_reader = BufReader::new(File::open("tests/fixtures/canonical/good-feature.geojson")?);

let feature: Feature = serde_json::from_reader(file_reader)?;

let geojson: GeoJson = feature.into();

println!("{}", &geojson.clone().to_string()?);
println!("{}", &geojson.to_string_pretty()?);

Ok(())
}
14 changes: 14 additions & 0 deletions src/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,20 @@ impl GeoJson {
{
serde_json::from_reader(rdr)
}

/// Convenience wrapper for [serde_json::to_string()]
pub fn to_string(self) -> Result<String> {
::serde_json::to_string(&self)
.map_err(|err| Error::MalformedJson(err))
.and_then(|s| Ok(s.to_string()))
}

/// Convenience wrapper for [serde_json::to_string_pretty()]
pub fn to_string_pretty(self) -> Result<String> {
::serde_json::to_string_pretty(&self)
.map_err(|err| Error::MalformedJson(err))
.and_then(|s| Ok(s.to_string()))
}
}

impl TryFrom<JsonObject> for GeoJson {
Expand Down

0 comments on commit 5d033b6

Please sign in to comment.