Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add from_json_value for GeoJson enum #119

Merged
merged 1 commit into from
Nov 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion src/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::json::{self, Deserialize, Deserializer, JsonObject, Serialize, Serializer};
use crate::json::{self, Deserialize, Deserializer, JsonObject, JsonValue, Serialize, Serializer};
use crate::serde;
use crate::{Error, Feature, FeatureCollection, Geometry};
use std::fmt;
Expand Down Expand Up @@ -77,6 +77,45 @@ impl GeoJson {
}
}
}

/// Converts a JSON Value into a GeoJson object.
///
/// # Example
/// ```
/// use geojson::{Feature, GeoJson, Geometry, Value};
/// use serde_json::json;
///
/// let json_value = json!({
/// "type": "Feature",
/// "geometry": {
/// "type": "Point",
/// "coordinates": [102.0, 0.5]
/// },
/// "properties": null,
/// });
///
/// assert!(json_value.is_object());
///
/// let geojson = GeoJson::from_json_value(json_value).unwrap();
///
/// assert_eq!(
/// geojson,
/// GeoJson::Feature(Feature {
/// bbox: None,
/// geometry: Some(Geometry::new(Value::Point(vec![102.0, 0.5]))),
/// id: None,
/// properties: None,
/// foreign_members: None,
/// })
/// );
/// ```
pub fn from_json_value(value: JsonValue) -> Result<Self, Error> {
if let JsonValue::Object(obj) = value {
Self::from_json_object(obj)
} else {
Err(Error::GeoJsonExpectedObject)
}
}
}

#[derive(PartialEq, Clone, Copy)]
Expand Down Expand Up @@ -188,3 +227,36 @@ impl fmt::Display for FeatureCollection {
.and_then(|s| f.write_str(&s))
}
}

#[cfg(test)]
mod tests {
use crate::{Feature, GeoJson, Geometry, Value};
use serde_json::json;

#[test]
fn test_geojson_from_value() {
let json_value = json!({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": null,
});

assert!(json_value.is_object());

let geojson = GeoJson::from_json_value(json_value).unwrap();

assert_eq!(
geojson,
GeoJson::Feature(Feature {
bbox: None,
geometry: Some(Geometry::new(Value::Point(vec![102.0, 0.5]))),
id: None,
properties: None,
foreign_members: None,
})
);
}
}