抱歉,这个问题可能很愚蠢,我是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中进行任何更改,因此我怀疑该错误可能是由于缺少依赖项或导入或其他内容引起的,但我无法弄清楚。
这是我得到空对象的地方
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,“ Data:” + arg.toString());可以正常工作,并记录数据字符串。 您是否需要其他解决方案? 预先感谢
答案 0 :(得分:0)
尝试一下:
JsonObject output = Json.createObjectBuilder()
.add("data", arg.toString())
.build();
return output;