生成JSONObject字符串键 [英] Generify JSONObject string keys

查看:72
本文介绍了生成JSONObject字符串键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用 org.json.JSONObject 的迭代器

JSONObject obj = new JSONObject();
obj.put("key1", "value1");
obj.put("key2", "value2");
Iterator keys = obj.keys();
...

带有编译警告


Iterator is a raw type. References to generic type Iterator<E> should be parameterized


我可以更新为通用版本:

I can update to generic version:

Iterator<?> keys = obj.keys();

但是没有办法生成 JSONObject String 键?

But isn't there a way to "generify" JSONObject with String keys?

我发现此答案,但其建议未编译

I find this answer but its suggestion doesn't compiled


JSONObject<String,Object> obj=new JSONObject<String,Object>();


EDIT

使用 Iterator< String> keys = obj.keys(); 我收到类型安全警告:

Using Iterator<String> keys = obj.keys(); I'm getting a type safety warning:


Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<String>


也使用Eclipse Infer泛型不会执行任何代码更改

Also using Eclipse Infer generics doesn't execute any code changes

推荐答案

您提供的链接答案所使用的类别与您使用的类别不同。如果您在中查找 org.json.JSONObject ,您将找到以下内容:

The answer you provided a link to is using a different class than the one you are using. If you look at the source for org.json.JSONObject you'll find the following:

public Iterator<String> keys() {
    return this.keySet().iterator();
}

这意味着您可以编写以下代码:

Which means you can write the following code:

    JSONObject obj = new JSONObject();
    obj.put("key1", "value1");
    obj.put("key2", "value2");
    Iterator<String> keys = obj.keys();

    while(keys.hasNext()){
        System.out.println(keys.next());
    }

它将生成以下输出:

key1
key2

这篇关于生成JSONObject字符串键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆