简体   繁体   中英

How to convert a string to JSON?

I'm using volley to get a file from the internet, the file is an array. I'm saving the file in cache to do this I have to convert the file into a string. I have a function that reads the cache and pass the response to another file to display the information, but when i'm trying to convert the resoionse back to an array i get an error

Value AuthStatus of type java.lang.String cannot be converted to JSONObject

I'm really new on android, hoping someone can point me on the right direction

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();
    } 
}

You have to use JSONValue.parse method as shown below:

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();
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM