简体   繁体   English

java(android)从头开始创建JSONObject

[英]java (android) create JSONObject from scratch

I'm trying to do something like: 我正在尝试做类似的事情:

public static final JSONObject MYOBJ = new JSONObject().put("value", "expression");

but eclipse get's mad and says there's an error on the line even though the tool tip shows No solutions available 但是蚀使人发狂,并说即使工具提示显示No solutions available ,生产线上也存在错误

I've tried changing JSONObject to type String and still the same prob. 我尝试将JSONObject更改为String并仍然使用相同的概率。 I'm shying away from hash maps and would really like to use JSON. 我回避了哈希映射,并且非常想使用JSON。

** EDIT - code location ** **编辑-代码位置**

package ...

import ...

public class MyActivity extends Activity {
    public static final JSONObject MYOBJ = new JSONObject().put("value", "expression");

    ... // onCreate etc
}

Well it seems the JSONObject has a checked exception that must be handled. 好吧,似乎JSONObject有一个必须处理的检查异常。 Try this 尝试这个

public static final JSONObject MYOBJ = new JSONObject(){
    {
        try {
            put("value", "expression");
        } catch(Exception e){
            e.printStackTrace();
        }
    }
};

The result of put() is an Object. put()的结果是一个对象。 Do it in two lines and all is well. 分两行进行,一切都很好。

public static final JSONObject MYOBJ = new JSONObject();
static {
  MYOBJ.put("value", "expression");
}

Note that the static final doesn't prevent the object from being changed, just that the original reference MYOBJ will always be the same object. 请注意,静态final不会阻止更改对象,只是原始引用MYOBJ将始终是同一对象。

Edit: Ah, I was probably using a different flavor of the JSON library. 编辑:啊,我可能正在使用不同风格的JSON库。 Nonetheless, the above approach will probably work nicely. 尽管如此,以上方法可能会很好地工作。 If the types all match, add some more parens to the original line. 如果所有类型都匹配,请在原始行中添加更多的括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM