【发布时间】:2019-09-05 20:29:34
【问题描述】:
我正在使用 Java 库 Volley 来处理我的网络请求。
对于 POST,我想使用 JsonArrayRequest 类,但我注意到由于 JSON 数组内部转换为带有 toString() 的字符串,JSON 数组中出现的所有斜杠都被转义,因此输出字符串为 "\/"而不是"/"。
由于我的 JSON 数组包含带有斜杠的字符串,我复制并粘贴了原始的 JsonArrayRequest 类,将其重命名并添加了.replaceAll("\\\\",""),以便从toString() 生成的字符串中删除所有反斜杠。
它可以正常工作。
这是Java代码:
public class MyJsonArrayRequest extends JsonRequest<JSONArray> {
public MyJsonArrayRequest(
String url, Listener<JSONArray> listener, @Nullable ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
public MyJsonArrayRequest(
int method,
String url,
@Nullable JSONArray jsonRequest,
Listener<JSONArray> listener,
@Nullable ErrorListener errorListener) {
super(
method,
url,
jsonRequest.toString().replaceAll("\\\\",""),
listener,
errorListener);
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(
response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(
new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
但是,由于我在我的项目中使用 Kotlin,我更喜欢将 Java 代码转换为 Kotlin 代码(我知道 Java 类可以很好地与 Kotlin 配合使用,这只是一种偏好和一些练习,可以更好地理解 Kotlin)。
这是 Kotlin 代码:
open class MyJsonArrayRequest2: JsonRequest<JSONArray>{
constructor(url: String, listener: Listener<JSONArray>, errorListener: ErrorListener):
super(Method.GET, url, null, listener, errorListener)
constructor(method: Int, url: String, jsonRequest: JSONArray, listener: Listener<JSONArray>, errorListener: ErrorListener):
super(method, url, jsonRequest.toString().replace("\\\\",""), listener, errorListener)
override fun parseNetworkResponse(response: NetworkResponse?): Response<JSONArray>{
try{
val jsonString = String(response!!.data, Charset.forName(HttpHeaderParser.parseCharset(response.headers)));
return Response.success(JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
}catch (e: UnsupportedEncodingException){
return Response.error(ParseError(e));
}catch (je: JSONException){
return Response.error(ParseError(je));
}
}
}
如果我现在运行我的应用程序(它编译时没有错误或警告),所有请求都使用MyJsonArrayRequest2 而不是MyJsonArrayRequest,我会收到kotlin.KotlinNullPointerException 错误。
编辑: 我现在明白了:使用Java类时响应不为空,但使用Kotlin类时响应为空。 出现的问题是可能导致这种差异的类之间的差异是什么?
我还检查了从 Java 到 Kotlin 的自动翻译,但除了自动翻译使用 replaceAll() 而不是 replace() 并且省略了一些 !! 和 ? 之外,我没有发现很多差异。然而,replaceAll() 我得到了一个“未解析的引用”错误,我在某处读到 Kotlin 的 replace() 与 Java 的 replaceAll() 相同。
【问题讨论】:
-
您想知道为什么会出现空指针异常吗?
标签: java kotlin android-volley