1

I've written a Java Method for an Android Studio (3.0.1) project that creates a JSONObject from a String. Now I've written a JUnit test to test that the JSON object is correct.

The problem is always that the JSONObject is NULL.

For example, I tried running the following code:

String response = "{\"songs\":\"title\"}";
System.out.println(response);
JSONObject submitPlaylistResponse = new JSONObject(response);
System.out.println(submitPlaylistResponse.toString());

The output is:

{"songs":"title"}
null

Why is my JsonObject still null? What am I missing? I feel like I'm missing something trivial/simple.

8
  • If you replace JSONObject submitPlaylistResponse = new JSONObject(response); with JSONObject submitPlaylistResponse = new JSONObject("{\"songs\":\"title\"}"); what do you get ? Commented Nov 21, 2017 at 2:46
  • What is your import for JSONObject Commented Nov 21, 2017 at 2:59
  • try this one System.out.println(submitPlaylistResponse.getString("songs")); Commented Nov 21, 2017 at 3:06
  • @android_Muncher: same thing - null object. Import is import org.json.*; Commented Nov 21, 2017 at 3:15
  • @G.Dator: same issue occurs. Commented Nov 21, 2017 at 3:20

3 Answers 3

3

After viewing JSONObject code I found this:

public String toString() {
   return "null";
}

As you see, method always returns "null" string not null object. In this case, if the task is to check the correctness of your JSONObject you can follow @G.Dator answer or use String toString (int indentSpaces).

See also.

Sign up to request clarification or add additional context in comments.

1 Comment

looks like toString(int indentFactor) is also broken. How in the world does someone introduce a bug like this when it worked in previous versions?! I guess people rewrite classes. This is why I keep 3rd party libraries to a minimum (though org.json was the one I had the most trust in until now).
1

Add below line to build.gradle dependencies

testImplementation 'org.json:json:20190722'

Refer this question for more details.

Comments

0

Probably you are using wrong library. Check your import. It must be like this. org.json.JSONObject; I've checked your code and it's working on my android studio 2.3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.