Android Universal Resolution Json

Keywords: JSON Java

The previous article has introduced the principle of universal parsing Json, but all the code written in one class loses the role of reuse, so the code is extracted and written in a single class.

Explain the operation in detail

Json data is converted into hashmap (JsonToHashMap.class)

public class JsonToHashMap {
    String url;
    Handler handler;
    public JsonToHashMap(String url, Handler handler){
        this.url=url;
        this.handler=handler;//note 1
        sendRequsetWithOKHttp(url);
    }

    public void sendRequsetWithOKHttp(String Url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //Time-consuming operations on new threads
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(Url).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    LinkedHashMap<String,Object> hashMaps=stringToJsonObject(responseData);
                    Message message=new Message();
                    message.obj=hashMaps;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*
     * Put Json data into hashmap
     * @param response
     * @return
     */

    private LinkedHashMap<String, Object> stringToJsonObject(String response) {
        try {
            Object json=new JSONTokener(response).nextValue();
            if(json instanceof JSONObject){
                JSONObject jso = new JSONObject(response);
                return JsonObjectToHashMap(jso);
            }else{
                JSONArray jsa=new JSONArray(response);
                return JsonArrayToHashMap(jsa);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }


    }

    private LinkedHashMap<String, Object> JsonObjectToHashMap(JSONObject jso) {
        LinkedHashMap<String, Object> hashmap = new LinkedHashMap<>();
        try {
            for (Iterator<String> keyStr = jso.keys(); keyStr.hasNext(); ) {
                String key1 = keyStr.next().trim();
                if (jso.get(key1) instanceof JSONObject) {
                    JSONObject NextJSONObject=new JSONObject(jso.get(key1).toString());
                    hashmap.put(key1, JsonObjectToHashMap(NextJSONObject));
                }else if(jso.get(key1) instanceof JSONArray) {
                    JSONArray NextJSONArray =new JSONArray(jso.get(key1).toString());
                    hashmap.put(key1, JsonArrayToHashMap(NextJSONArray));
                }else {
                    hashmap.put(key1, jso.get(key1));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return hashmap;
    }
    private LinkedHashMap<String, Object> JsonArrayToHashMap(JSONArray jsa){
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
        try {
            for (int i = 0; i < jsa.length(); i++) {
                if(jsa.get(i) instanceof JSONArray) {
                    JSONArray NextJSONArray=new JSONArray(jsa.get(i).toString());
                    hashMap.put(String.valueOf(i), JsonArrayToHashMap(NextJSONArray));
                }else if(jsa.get(i) instanceof JSONObject){
                    JSONObject NextJSONObject=new JSONObject(jsa.get(i).toString());
                    hashMap.put(String.valueOf(i),JsonObjectToHashMap(NextJSONObject));
                }
            }
        }catch (JSONException e){
            e.getStackTrace();
        }
        return hashMap;
    }

}

Note 1: Because extracting Json data from a Web site is done in a real thread, getting hashmap in handler cannot be returned to the class calling the method.
(If there is any God who points out how to return, please give more advice), so the handler's operation uninstalls the call class.

Extracting data from hashmap (JsonForOne.class)

public class JsonForOne {
    static Object songs;
    public static String getpoint(LinkedHashMap<String, Object> LinkedHashMap, String[] s){
        String get=null;
        String[] sr=s;
        java.util.LinkedHashMap<String ,Object> linked=LinkedHashMap;
        for(int i = 0;i<sr.length;i++){
            songs=linked.get(sr[i]);
            if(songs instanceof java.util.LinkedHashMap){
                linked=(java.util.LinkedHashMap<String ,Object>)songs;
                continue;
            }else {
                get=songs.toString();
            }
        }
        return get;
    }
}

Usage method

Handler handler=new Handler(){
            public void handleMessage(Message msg) {
                hashMap=((LinkedHashMap<String, Object>)msg.obj);
                Processing(hashMap);
            }
        };
JsonToHashMap j=new JsonToHashMap("url",handler);

public void Processing(LinkedHashMap<String, Object> map){
//Specific operation
String[] name = { "key1 value", "key2 value"};//key1 and key2 are nested relationships
String s = JsonForOne.getpoint(hashMap, name)//Simple Json Data Acquisition
}

This is the complete version of the Universal Json Data Method, which can greatly reduce the repetition of the code.

Posted by MickeyAsh on Fri, 05 Apr 2019 11:09:31 -0700