java - 如何在 Java 中将映射值转换为字符串

标签 java dictionary

我能够以这种格式打印输出 System.out.println(map.get("email"));//打印正常 但我无法打印将其分配给 String 变量后的相同值。我试过: String email=(String) map.get("email"); System.out.println("Email--"+email);//但这不是打印
如何将 map 值转换为字符串?请帮我。

我的完整代码:

String url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token="
              + authResponse.accessToken; 
            final StringBuffer r = new StringBuffer(); 
            final URL u = new URL(url);
            final URLConnection uc = u.openConnection();
            final int end = 1000;
            InputStreamReader isr = null;
            BufferedReader br = null; 
            isr = new InputStreamReader(uc.getInputStream());
            br = new BufferedReader(isr);
            final int chk = 0; 
            String pat = "\"(.*)\": \"(.*)\",";
            Pattern pattern = Pattern.compile(pat);
            Matcher matcher = null;
            Map map = new HashMap();

            while ((url = br.readLine()) != null)
            {
                if ((chk >= 0) && ((chk < end))) {
                    matcher = pattern.matcher(url);
                    if(matcher.find()) {
                        map.put(matcher.group(1), matcher.group(2));
                    }
                    //r.append(url).append('\n');
                }
            }
              System.out.println(map.get("email")); 
              String email=(String) map.get("email"); 
              System.out.println(email);

最佳答案

在使用任何集合或 map 时始终使用泛型类型,除非您使用的 Java 版本早于 1.5。因此,将您的 map 声明为:-

Map<String, String> map = new HashMap<String, String>();

然后你就根本不需要类型转换了。 map.get("email") 只会给你 String 类型的结果。

关于java - 如何在 Java 中将映射值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303264/

相关文章:

java - 如何将图像从 Android 上传到 Google Cloud (Java)?

java - 从数组创建适配器(AutoCompleteTextView)

java - 如何访问 JavaFx 2.0 中的 Controller 类?

python - Python 脚本中的关键错误

python - 使用生成器表达式加载选项字典

powershell - 字典计数 vs 计数键

java - Jackson - 将 Map 实现反序列化为 HashMap

Java Pattern.matcher(StringBuffer),为什么它的行为与 Pattern.matcher(String) 不同?

c++ - 如何完全管理 std 容器(如 map)的堆内存分配?

python - 循环时使用键对字典项目进行排序