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

include module from the same directory level [duplicate]
Is there a way to prevent emitted LLVM IR from removing unused functions?
Does Cargo support custom profiles?
Pass mutable reference to an element of a vector as parameter of function alongside with that vector
How to format a String object in Rust? [duplicate]
How do I make rustc-link-search relative to the project location?
Safe non-trivial data dependencies/custom references?
Skip struct field when serializing
Rust error E0495 using split_at_mut in a closure
What is the proper way to create a Span when inserting a new field with a Rust compiler plugin?
Using Any with traits in Rust [duplicate]
How do I create an iterator that invalidates the previous result each time `next` is called? [duplicate]
How can I better store a string to avoid many clones?
What's the difference between immutable and mutable references to an i32 when adding?
How to return either a reference or newly created data? [duplicate]
Idiomatic way to store a closure for reuse?

Categories

HOME
android-espresso
class
lambda
cucumber
openxml
focus
adfs3.0
barcode-scanner
softlayer
selenium-builder
activex
devexpress
activemq
azure-data-lake
onvif
minecraft
telegraf
responsive-design
hystrix
cqrs
getopenfilename
fbloginview
sap-fiori
rangy
django-rq
pinterest
closures
exe
angular2-highcharts
anova
neo4j.rb
sharedpreferences
maven-surefire-plugin
ini
perfino
cell
opentext
data-collection
background-color
xdebug
list-comprehension
hevc
bitbake
es6-modules
argv
private-key
osx-lion
custom-keyboard
adminer
spinner
fastlane
selenide
assemblies
cloudera-sentry
distributed-caching
vungle-ads
contactless-smartcard
apache-toree
axis
libreoffice-writer
sonatype
iptv
algebra
apache-modules
emacs25
front-camera
oid
petsc
tsqlt
system.net.mail
yii2-model
node-glob
jeasyui
jeditable
vaadin4spring
teamviewer
bayesglm
godeps
juniper-network-connect
http.client
screen-orientation
sqlbase
kefir.js
flow-js
console.log
shoes
nanomsg
operands
wicket-1.5
cout
inputbox
windows-rt
visual-c++-2012
coding-efficiency
refit
cidr
jchartfx
meteorite
discovery
mousemotionlistener
unrealscript
sql-view
mp4parser
libxml-js
quickgraph
dibs
tridion-2011
gitx
playorm
kolite
memory-pool
datacontracts
tablet-pc
tabbarcontroller
ppc
processors
downcasting
xap
bindable-linq
synthesizer

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App