java - 如何将字符串转换为 JSON?
问题描述
我正在使用 volley 从互联网上获取文件,该文件是一个数组。我将文件保存在缓存中为此我必须将文件转换为字符串。我有一个读取缓存并将响应传递给另一个文件以显示信息的函数,但是当我尝试将 resoionse 转换回数组时出现错误
Value AuthStatus of type java.lang.String cannot be converted to JSONObject
我对android很陌生,希望有人能指出我正确的方向
private void cacheFile(JSONObject response) {
JSONObject res = response;
String filename = "jsonfile";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(res.toString().getBytes("utf-8"));
outputStream.close();
Log.e(TAG, "Bien");
} catch (Exception e) {
e.printStackTrace();
}
}
private void readCache(String filename) {
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
inputStream.read();
String body = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
inputStream.close();
fromCache(body);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fromCache(String json) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("cars");
Log.e(TAG, "Array Size: " + jsonArray.length());
} catch (JSONException e) {
e.printStackTrace();
}
}
解决方案
您必须使用 JSONValue.parse 方法,如下所示:
public void fromCache(String json) {
JSONObject jsonObject = null;
try {
jsonObject = (JSONObject)JSONValue.parse(json);
JSONArray jsonArray = jsonObject.getJSONArray("cars");
Log.e(TAG, "Array Size: " + jsonArray.length());
} catch (JSONException e) {
e.printStackTrace();
}
}
推荐阅读
- modal-dialog - SharePoint 颜色选择器模式对话框不自动调整
- firebase - 当我通过 Firebase 云消息传递发送推送通知时,我的 React Native 应用程序关闭
- angular - 在 Angular 5 中等待多个 Observables
- twitter-bootstrap - How to change column width based on the number of columns present?
- c# - VS IDE 设置,以获得更多代码空间
- oracle - plsql varchar2中的增量函数
- etl - 使用 AWS Glue 将 CSV 转换为 ORC 时如何排除分区?
- php - nginx 不提供 php 但下载
- scala - 是否可以从 spark job 获取集群的物理设置?
- arrays - 如果嵌套对象在所有嵌套对象上的特定属性为 false,则删除父对象