将json转换为TreeMap< String,String>

编程入门 行业动态 更新时间:2024-10-10 21:29:54
本文介绍了将json转换为TreeMap< String,String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想以一种简单的方式将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&lt; String,String&gt;

本文发布于:2023-11-12 12:59:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   TreeMap   json   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!