【发布时间】:2016-09-20 05:24:53
【问题描述】:
我需要下载 JSON,然后将其存储在 JSONObject 中。
我正在使用 org.json.JSONArray。
所有代码都集中在一个地方:
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;
}
}
测试方法
@Test
public void addition_isCorrect() throws Exception
{
JSONObject json = Test.getJSON();
assertNotNull(json);
assertTrue(json.length()>0);
}
第一个断言通过,第二个没有,导致长度 == 0。
我得到的是this。值为字符串“null”的 JSONObject 对象。
不抛出异常。我将缓冲区的内容写入文件并对其进行了验证,并且验证良好。
另一张图http://i.imgur.com/P03MiEZ.png
为什么会这样?
分级
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.+'
}
【问题讨论】:
-
我认为您在添加该对象的值后需要一个 断点。尝试在
return之前添加一个虚拟行,如Log.i("tag", "DUMMY");并在其上放置断点。 -
这里
JSONObject类属于哪个库??是google.simple.json还是apatche??哪一个这真的让我们很困惑,因为你没有提到导入语句。@LLL -
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));告诉它使用 unicode 解码器。 -
**** 看看这个:stackoverflow.com/questions/29402155/…
-
由于您在单元测试中运行它,这没有使用任何设备上的库,SDK 不提供代码,只是一个签名,我猜是返回“null”;)尝试将 jar 包含在 gradle 中以查看结果。
标签: java android jsonobject