JAVA: How to Read JSON Format Data (Web Game Development)

Here is a example code on how to read Json format datas for web game development.

 

How to Read JSON Format Data with JAVA

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
*
* @param result JSON string
* @param name JSON array name
* @param fields The fields contained in the JSON string
* @return Returns a list of type List<Map<String,Object>>, Map<String,Object> corresponding to the structure "id": "1"
*/
public static List<Map<String, Object>> convertJSON2List(String result,
String name, String[] fields) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
JSONArray array = new JSONObject(result).getJSONArray(name);
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.opt(i);
Map<String, Object> map = new HashMap<String, Object>();
for (String str : fields) {
map.put(str, object.get(str));
}
list.add(map);
}
} catch (JSONException e) {
Log.e("error", e.getMessage());
}
return list;
}
/** * * @param result JSON string * @param name JSON array name * @param fields The fields contained in the JSON string * @return Returns a list of type List<Map<String,Object>>, Map<String,Object> corresponding to the structure "id": "1" */ public static List<Map<String, Object>> convertJSON2List(String result, String name, String[] fields) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { JSONArray array = new JSONObject(result).getJSONArray(name); for (int i = 0; i < array.length(); i++) { JSONObject object = (JSONObject) array.opt(i); Map<String, Object> map = new HashMap<String, Object>(); for (String str : fields) { map.put(str, object.get(str)); } list.add(map); } } catch (JSONException e) { Log.e("error", e.getMessage()); } return list; }
/** 
 *  
 * @param result JSON string 
 * @param name JSON array name 
 * @param fields The fields contained in the JSON string 
 * @return Returns a list of type List<Map<String,Object>>, Map<String,Object> corresponding to the structure "id": "1" 
 */  
public static List<Map<String, Object>> convertJSON2List(String result,  
        String name, String[] fields) {  
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
    try {  
        JSONArray array = new JSONObject(result).getJSONArray(name);  
 
        for (int i = 0; i < array.length(); i++) {  
            JSONObject object = (JSONObject) array.opt(i);  
            Map<String, Object> map = new HashMap<String, Object>();  
            for (String str : fields) {  
                map.put(str, object.get(str));  
            }  
            list.add(map);  
        }  
    } catch (JSONException e) {  
        Log.e("error", e.getMessage());  
    }  
    return list;  
}

 

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *