【发布时间】:2018-11-21 17:27:59
【问题描述】:
对于这个可能很愚蠢的问题,我很抱歉,我是 Java、Android Studio 和所有相关内容的新手。 我正在尝试使用DarkSkyApi 在Android Studio 3.2.1 上为android 实现一个简单的天气预报应用程序。 我设法使用 HttpsURLConnection、StringBuilder 从 DarkSky 的服务器获取数据 和 BufferedReader。但是,当我尝试创建一个新的 JSONObject(.toString()) 时,它只返回 null。进一步调查将我带到 .toString()->JSONObject.java->JSONStringer,其中 Android Studio“无法访问 org.json.JSONStringer.Scope”,似乎是导致 .toString() 失败的原因。 我确实添加了 JSON-Library,除了 JSONStringer 之外,所有与 JSON 相关的东西看起来都可以工作。进口在我看来也不错。 这是故障代码:
public class JSONStringer {
/** The output data, containing at most one top-level array or object. */
final StringBuilder out = new StringBuilder();
/**
* Lexical scoping elements within this stringer, necessary to insert the
* appropriate separator characters (ie. commas and colons) and to detect
* nesting errors.
*/
枚举范围{
/**
* An array with no elements requires no separators or newlines before
* it is closed.
*/
EMPTY_ARRAY,
/**
* A array with at least one value requires a comma and newline before
* the next element.
*/
NONEMPTY_ARRAY,
/**
* An object with no keys or values requires no separators or newlines
* before it is closed.
*/
EMPTY_OBJECT,
/**
* An object whose most recent element is a key. The next element must
* be a value.
*/
DANGLING_KEY,
/**
* An object with at least one name/value pair requires a comma and
* newline before the next element.
*/
NONEMPTY_OBJECT,
/**
* A special bracketless array needed by JSONStringer.join() and
* JSONObject.quote() only. Not used for JSON encoding.
*/
NULL,
}
由于我没有更改 JSONStringer.java 中的任何内容,我怀疑该错误可能与缺少依赖项或导入或其他内容有关,但我无法弄清楚。
这就是我得到 Null-Object 的地方
if (responceCode == HttpURLConnection.HTTP_OK)
{
Log.i(TAG, "CONNECTION:::" + connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
Log.i(TAG, "url:::");
StringBuilder arg = new StringBuilder(1024);
String tmp="1";
while(tmp !=null) {
tmp = reader.readLine();
arg.append(tmp).append("\n");
}
reader.close();
Log.i(TAG, "Data: " + arg.toString());
return new JSONObject(arg.toString());
}
else{
return null;
}
Log.i(TAG, "数据:" + arg.toString());工作正常并按应有的方式记录数据字符串。 你需要别的东西来解决这个问题吗? 提前致谢
【问题讨论】:
-
我通过使用 String.split() 手动提取数据来解决 JSON 库问题 不完美,但我得到了我想要的
标签: java android json android-studio