【问题标题】:How to convert a string to JSON?如何将字符串转换为 JSON?
【发布时间】:2019-05-01 16:34:15
【问题描述】:

我正在使用 volley 从 Internet 获取文件,该文件是一个数组。我将文件保存在缓存中为此我必须将文件转换为字符串。我有一个读取缓存并将响应传递给另一个文件以显示的函数 信息,但是当我尝试将 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();
    } 
}

【问题讨论】:

    标签: java android arrays json


    【解决方案1】:

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

    【讨论】:

    • 谢谢,你知道为什么 android studio 不能识别 JSONValue
    猜你喜欢
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2016-12-06
    • 2020-05-08
    相关资源
    最近更新 更多