conversion from string to json object android

后端 未结 8 1893
误落风尘
误落风尘 2020-11-30 00:39

I am working on an Android application. In my app I have to convert a string to Json Object, then parse the values. I checked for a solution in stackoverflow and found simil

8条回答
  •  孤城傲影
    2020-11-30 01:32

    To get a JSONObject or JSONArray from a String I've created this class:

    public static class JSON {
    
         public Object obj = null;
         public boolean isJsonArray = false;
    
         JSON(Object obj, boolean isJsonArray){
             this.obj = obj;
             this.isJsonArray = isJsonArray;
         }
    }
    

    Here to get the JSON:

    public static JSON fromStringToJSON(String jsonString){
    
        boolean isJsonArray = false;
        Object obj = null;
    
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            Log.d("JSON", jsonArray.toString());
            obj = jsonArray;
            isJsonArray = true;
        }
        catch (Throwable t) {
            Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
        }
    
        if (object == null) {
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                Log.d("JSON", jsonObject.toString());
                obj = jsonObject;
                isJsonArray = false;
            } catch (Throwable t) {
                Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
            }
        }
    
        return new JSON(obj, isJsonArray);
    }
    

    Example:

    JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
    if (json.obj != null) {
    
        // If the String is a JSON array
        if (json.isJsonArray) {
            JSONArray jsonArray = (JSONArray) json.obj;
        }
        // If it's a JSON object
        else {
            JSONObject jsonObject = (JSONObject) json.obj;
        }
    }
    

提交回复
热议问题