rust


Convert a serde Map into Value


As per the Serde specification, an Object / Map<String, Value> is a Value:
pub enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
Yet when I compile this code:
#![feature(use_extern_macros)]
extern crate serde;
#[macro_use]
extern crate serde_json;
#[derive(Debug)]
struct Wrapper {
ok: bool,
data: Option<serde_json::Value>,
}
impl Wrapper {
fn ok() -> Wrapper {
Wrapper {
ok: true,
data: None,
}
}
pub fn data(&mut self, data: serde_json::Value) -> &mut Wrapper {
self.data = Some(data);
self
}
pub fn finalize(self) -> Wrapper {
self
}
}
trait IsValidWrapper {
fn is_valid_wrapper(&self) -> bool;
}
impl IsValidWrapper for serde_json::Map<std::string::String, serde_json::Value> {
fn is_valid_wrapper(&self) -> bool {
self["ok"].as_bool().unwrap_or(false)
}
}
fn main() {
let json = json!({
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
});
let converted_json: Wrapper = json.as_object()
.map_or_else(
|| Err(json),
|obj| {
if obj.is_valid_wrapper() {
Ok(
Wrapper::ok()
.data(obj["data"].clone())
.finalize()
)
} else {
Err(*obj as serde_json::Value)
}
}
).unwrap_or_else(|data| Wrapper::ok().data(data.clone()).finalize() );
println!("org json = {:?} => converted json = {:?}", json, converted_json);
}
I get this error:
Compiling tests v0.1.0 (file:///Users/bgbahoue/Projects.nosync/tests)
error: non-scalar cast: `serde_json::Map<std::string::String, serde_json::Value>` as `serde_json::Value`
--> src/main.rs:64:21
|
64 | Err(*obj as serde_json::Value)
| ^^^^^^^^^^^^^^^^^^^^^^^^^
Is there a way to downcast a Map into a Value?
an Object / Map<String, Value> is a Value
No, it is not. Value is a type. Map<String, Value> is a type. Value::Object is an enum variant, which is not a separate type. In this case, Value::Object holds another value of type Map<String, Value>. You have to wrap the value in the variant to convert the type:
Err(serde_json::Value::Object(obj))
This will lead you to the problem:
expected type `serde_json::Map<std::string::String, serde_json::Value>`
found type `&serde_json::Map<std::string::String, serde_json::Value>`
as_object returns a reference to the contained object (if it's present), not the value itself. You will need to match on it for now:
let converted_json = match json {
serde_json::Value::Object(obj) => {}
_ => {}
};

Related Links

Why is variable scope dependent on the definition order?
Warning on “unstable” directive
How can I pass a socket as an argument to a function being called within a thread?
error: cannot move out of borrowed content on &mut self
Why does a reference not live long enough in case of “as_slice”?
Getting the error “error: the trait `core::marker::Sized` is not implemented” when trying to return the value from a vector
Traits with associated type in templates
Error handling best-practices
How to call count on an iterator and still use the iterator's items?
Caught between a lifetime and an FFI place
How to swap elements of array?
error: cannot assign to immutable indexed content `i[..]`
How to make a vector of received size?
Make an argument of type BTreeMap optional [closed]
Why can I assign a negative number to an unsigned integer variable?
Can a while loop evaluate to a value?

Categories

HOME
php
spring-data
generics
tomcat
d3.js
celery
dronekit-python
portable-class-library
flurry
azure-data-lake
drag-and-drop
angular2-template
cisco
migrate
sap-fiori
game-maker
grocery-crud
outlook-restapi
pinterest
jqxgrid
jitsi
gitkraken
anova
fluent-migrator
mime-types
amazon-sns
websphere-portal
unrar
msdeploy
running-object-table
sendmessage
seafile-server
restful-architecture
xerces-c
keyboard-layout
uivisualeffectview
eclipse-gmf
elastica
mars-simulator
extbase
resampling
hdiv
vungle-ads
asp.net-web-api-routing
lvalue
boost-compute
google-identity-toolkit
streamwriter
nunit-console
bbc-micro
yii2-model
maximize
sharepoint-apps
voronoi
godeps
pythonxy
mgwt
mod-auth-openidc
tkx
mojo
vs-unit-testing-framework
tabris
mobile-country-code
ecos
loginview
category-theory
incognito-mode
accountmanager
oxygene
lync-2010
application-blocks
grails-2.3
mousemotionlistener
sql-view
acceptance-testing
multiscaleimage
playorm
nsmutablestring
first-class
platform-independent
firebird1.5
acpi
kolite
filelock
database-deadlocks
fork-join
directshow.net
git-log
turbine
hungarian-notation
mygeneration
jdownloader
android-input-method
principles
rtti
sqlsitemapprovider
database-cloning
twitter-feed
code-camp
service-factory

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App