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.+'
}
returnlikeLog.i("tag", "DUMMY");and put a breakpoint on it.JSONObjectClass belongs to which library ?? is itgoogle.simple.jsonorapatche?? which one This really confused us because you have not mentioned the import statement.@LLLBufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));tells it to use the unicode decoder.