简体   繁体   中英

Get null when generating JSONObject with String

I'm now trying this code with JUnit.

try {
    JSONObject jsonObject = new JSONObject("{\"name\":\"foo\",\"id\":\"2\"}");
    String name = jsonObject.getString("name");
    Log.d(TAG, "name = " + name);
} catch (JSONException e) {
    e.printStackTrace();
}

I'm now testing put break point line at "Log.d...", but jsonObject always null. What is my mistake? This code is no problem on actual device.

You should get an error if it's improperly formatted JSON, so not sure why it would be null.

Just in case, though, I would personally avoid the need to escape the quotes in the string and individually put each key-value.

JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "foo");
jsonObject.put("id", "2");

This problem is related with my JUnit emviroment. I use this configuration.

testOptions {
    unitTests.returnDefaultValues = true
}

When I change this option false, this test invoke error like

java.lang.RuntimeException: Method put in org.json.JSONObject not mocked.

I could find a test using JSONObject can not be tested with usual way. It's lucky.

Thank you everyone comment to me.

Android JSON API is part of android its not part of Java API. ie they are not available to run on JVM they run on android environment.

If you want to use JSON API for unit testing you need to integrate below dependency in build.gradle file in android studio

testImplementation 'org.json:json:20140107'

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