简体   繁体   中英

I can't create an instance of JSONObject

Here is my code:

public String prepareParam(HashMap<String, String> params) {
    JSONObject json = new JSONObject(params);
    return json.toString();
}

According to Android developer documentation , a constructor with Map<String, String> is available. However, I got this exception:

Exception in thread "main" java.lang.RuntimeException: Stub!
at org.json.JSONObject.<init>(JSONObject.java:87)
at com.example.spc.utils.JSONPararmeterPrepareStaregy.prepareParam(JSONParameters.java:12)

Most probably you pass something wrong to prepareParam . Trivial junit test works fine:

public class JSONObjectTest {
    public String prepareParam(Map<String, String> params) {
        JSONObject json = new JSONObject(params);
        return json.toString();
    }

    @Test public void test(){
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        String str = prepareParam(map);
        assertEquals("error", "{\"key1\":\"value1\",\"key2\":\"value2\"}", str);
    }
}

BTW: It would be better if prepareParam accept Map<String, String> like JSONObject ctor does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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