首页 > 解决方案 > 如何将字符串转换为 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();
    } 
}

标签: javaandroidarraysjson

解决方案


您必须使用 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();
    } 
}

推荐阅读