我想以一种简单的方式将json转换为TreeMap,这是我的尝试:
I want to convert json to TreeMap in a simple way, here's my attempt:
extern crate serialize; use serialize::json; use serialize::json::ToJson; use serialize::json::Json; use std::collections::TreeMap; fn main() { let mut tree_map1 = TreeMap::new(); tree_map1.insert("key1".to_string(), "val1".to_json()); tree_map1.insert("key2".to_string(), "val2".to_json()); //... and so on, the number of keys aren't known let json1 = json::Object(tree_map1); let mut tree_map2 = TreeMap::new(); for (k, v) in json1.iter() { //impossible to iterate tree_map2.insert(k.to_string(), v.to_string()); } }更新:
如何将TreeMap<String, json::Json>转换为TreeMap<String, String>?
let json1 = get_json1(); // json made of TreeMap<String, json::Json> let res = match json1 { json::Object(json2) => json2.map(|k, v| ??? ), _ => panic!("Error") }推荐答案
json::Object是枚举变量,其中包含TreeMap.因此,为了从中获取TreeMap,您只需解开包装即可:
json::Object is an enum variant which contains TreeMap inside it. So in order to get a TreeMap from it, you just need to unwrap it:
let json1 = json::Object(tree_map1); let tree_map2 = match json1 { json::Object(tm) => tm, _ => unreachable!() };这将消耗json1.如果您不想要它,则需要克隆地图:
This will consume json1. If you don't want it, you need to clone the map:
let tree_map2 = match json1 { json::Object(ref tm) => tm.clone(), _ => unreachable!() };后者可以使用as_object()方法进行较小的重写:
The latter can be rewritten less noisily with as_object() method:
let tree_map2 = json1.as_object().unwrap().clone();如果需要从Object变体中包含的TreeMap<String, Json>获取TreeMap<String, String>,则需要以某种方式将Json转换为String.如果事先知道所有值都是JSON字符串,则可以再次使用模式匹配:
If you need to obtain TreeMap<String, String> from TreeMap<String, Json> which is contained inside Object variant, you need to convert Json to String somehow. If you know in advance that all values are JSON strings, you can use pattern matching again:
let tree_map2 = match json1 { json::Object(tm) => tm.into_iter().map(|(k, v)| (k, match v { json::String(s) => s, _ => unreachable!() })).collect(), _ => unreachable!() };更多推荐
将json转换为TreeMap< String,String>
发布评论