9

I need to download JSON and then store it in JSONObject.

I am using org.json.JSONArray.

Here's all the code in one place:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test
{
    public static JSONObject getJSON()
    {
    try
    {
        URL uri = new URL("http://events.makeable.dk/api/getEvents");
        HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
        {
            return null;
        }

        InputStream inputStream = urlConnection.getInputStream();

        if (inputStream != null)
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer buffer = new StringBuffer();

            try
            {
                String line;
                while ((line = br.readLine()) != null)
                {
                    buffer.append(line);
                }
                br.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }



            String json = buffer.toString();

            JSONObject jObject = null;
            try {
                jObject = new JSONObject(json);
            }
            catch (JSONException e) {
                e.printStackTrace();

            }
            int i = 1;
            return jObject;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
}

Testing method

 @Test
    public void addition_isCorrect() throws Exception
    {
        JSONObject json = Test.getJSON();
        assertNotNull(json);
        assertTrue(json.length()>0);
    }

First assert passes, the second doesn't, cause length == 0.

And what I get is this. A JSONObject object with value of string "null".

No exception is thrown. I wrote the contents of buffer to file and validated it, and it validates fine.

Another picture https://i.sstatic.net/Dw9ug.png

Why is it acting like this?

Gradle

apply plugin: 'com.android.application'

android {

testOptions {
    unitTests.returnDefaultValues = true
}
compileSdkVersion 23
buildToolsVersion "24.0.0 rc3"

defaultConfig {
    applicationId "baaa.myapplication"
    minSdkVersion 23
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.+'
}
44
  • 2
    I think you need a breakpoint after adding the value of that object. Try to add a dummy line before return like Log.i("tag", "DUMMY"); and put a breakpoint on it. Commented May 23, 2016 at 11:07
  • Here JSONObject Class belongs to which library ?? is it google.simple.json or apatche ?? which one This really confused us because you have not mentioned the import statement.@LLL Commented May 23, 2016 at 11:07
  • 1
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); tells it to use the unicode decoder. Commented May 23, 2016 at 11:27
  • 1
    **** look at this : stackoverflow.com/questions/29402155/… Commented May 23, 2016 at 12:15
  • 1
    Since you run it on unit tesing, this is not using the library from any device, the SDK doesn't provide the code, just a signature a I guess, a return "null" ;) Try to include the jar in the gradle to see the result. Commented May 23, 2016 at 12:16

4 Answers 4

12

Since you are running your code with Junit, it running on the SDK on your computer. This SDK doesn't provide everything, some are just some skeleton class providing signature of method and documentation but not the code. So you can't execute directly.

You need to import the library to be able to run it on testing.

testCompile 'org.json:json:the_correct_version'

See the version here :

http://mvnrepository.com/artifact/org.json/json

This is based on the answer on this post : Android unit test not mocked

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

5 Comments

Current version is : 20160212
And everything is happy in OP's lala land... :D
And OP lived happily ever after. Fin.
The correct version for Android is : org.json:json:20080701 otherwise you will have different behaviour in getString() for null. On Android it will return null, On earlier version it will throw an Exception
Can you give me some documentation on this Exception for post 2008 version ?
0

First convert json string into JSONArray then used that JSONArray object for getting the each JSONObject

1 Comment

JSONArray is also "null" if I do new JSONArray(json)
0

Please have a try of this

String json = buffer.toString();
JSONObject jsonObject = new JSONObject(json);
JsonObject updatedJson = jsonObject.optJSONObject("json");
return updatedJson;

1 Comment

i tried his code and i am getting the json value in jsonObject
-3

Dear you first try to get only json = buffer.toString(); tell me the value of json.

if your string json is null then problem in file reading code.

2 Comments

You can see from the image I posted that it's not null i.sstatic.net/DEvyW.png
Not an answer, in fact, pass that into this it is indeed valid.

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.