[英]JsonNode in JSON in Rust
I ran through the standard JSON library of Rust http://doc.rust-lang.org/serialize/json/ and couldn't figure out what represents a node in it. 我浏览了Rust的标准JSON库http://doc.rust-lang.org/serialize/json/ ,但无法弄清楚其中代表了一个节点。 In Java it's
JsonNode
. 在Java中,它是
JsonNode
。 What's it in Rust? Rust到底是什么? For example, how can I pass an argument of the type
JsonNode
in Rust? 例如,如何在Rust中传递
JsonNode
类型的参数?
Rust's "DOM" for JSON is defined by Json
enum. Rust的JSON的“ DOM”由
Json
枚举定义。 For example, this JSON object: 例如,以下JSON对象:
{ "array": [1, 2, 3], "submap": { "bool": true, "string": "abcde" } }
is represented by this expression in Rust: 由Rust中的此表达式表示:
macro_rules! tree_map {
($($k:expr -> $v:expr),*) => ({
let mut r = ::std::collections::TreeMap::new();
$(r.insert($k, $v);)*
r
})
}
let data = json::Object(tree_map! {
"array".to_string() -> json::List(vec![json::U64(1), json::U64(2), json::U64(3)]),
"submap".to_string() -> json::Object(tree_map! {
"bool".to_string() -> json::Boolean(true),
"string".to_string() -> json::String("abcde".to_string())
})
});
I've used custom map construction macro because unfortunately Rust standard library does not provide one (yet, I hope). 我使用了自定义地图构造宏,因为不幸的是Rust标准库没有提供一个(但是,我希望如此)。
Json
is just a regular enum, so you have to use pattern matching to extract values from it. Json
只是一个常规枚举,因此您必须使用模式匹配从中提取值。 Object
contains an instance of TreeMap
, so then you have to use its methods to inspect object structure: Object
包含TreeMap
的实例,因此您必须使用其方法检查对象结构:
if let json::Object(ref m) = data {
if let Some(value) = m.find_with(|k| "submap".cmp(k)) {
println!("Found value at 'submap' key: {}", value);
} else {
println!("'submap' key does not exist");
}
} else {
println!("data is not an object")
}
Update 更新
Apparently, Json
provides a lot of convenience methods, including find()
, which will return Option<&Json>
if the target is an Object
which has corresponding key: 显然,
Json
提供了许多便利的方法,包括find()
,如果目标是具有相应键的Object
,它将返回Option<&Json>
:
if let Some(value) = data.find("submap") {
println!("Found value at 'submap' key: {}", value);
} else {
println!("'submap' key does not exist or data is not an Object");
}
Thanks @ChrisMorgan for the finding. 感谢@ChrisMorgan的发现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.