Map 轉 Json

###Map<String, Object> 轉 Json (Android環境)json

public void onButtonClick(View view){

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> map0 = new HashMap<>();
    map0.put("q","1");
    map0.put("w","2");
    map0.put("e","3");

    List<Object> stringList = new ArrayList<>();
    stringList.add(map0);
    stringList.add(map0);
    stringList.add(map0);

    Map<String, Object> map1 = new HashMap<>();
    map1.put("j","1");
    map1.put("k","2");
    map1.put("l","3");
    map1.put("m",stringList);

    map.put("a", "1");
    map.put("b", "2");
    map.put("c", "3");
    map.put("stringList", stringList);
    map.put("map", map1);
    try {
        Log.d(TAG, mapToJson(map));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 *  將Map轉換成Json
 * @param jsonMap
 * @return
 * @throws Exception
 */
public String mapToJson( Map<String, Object> jsonMap ) throws Exception{
    StringBuilder result = new StringBuilder();
    result.append("{");
    Iterator<Map.Entry<String, Object>> entryIterator = jsonMap.entrySet().iterator();

    for(Map.Entry<String, Object> entry : jsonMap.entrySet()){

        String key = entry.getKey();
        Object value = entry.getValue();
        if(value instanceof  Map){
            System.out.println("\n Object Key : "+key);
            String mapJson = mapToJson((Map<String, Object>) value);
            result.append("\"").append(key).append("\":").append(mapJson);
        } else if(value instanceof List){
            System.out.println("\n Array Key : "+key);
            String listJson = listToJson((List) value);
            result.append("\"").append(key).append("\":").append(listJson);
        }else{
            System.out.println("key : "+key+" value : "+value);
            result.append("\"").append(key).append("\":\"").append(value).append("\"");
        }
        // 最後一個去掉 逗號
        entryIterator.next();
        if(entryIterator.hasNext()){
            result.append(",");
        }
    }
    result.append("}");
    return result.toString();
}

/**
 * 將List轉成Json
 * @param jsonList
 * @return
 * @throws Exception
 */
public String listToJson( List jsonList ) throws Exception {
    StringBuilder result = new StringBuilder();
    result.append("[");
    JSONArray jsonArray = new JSONArray(jsonList);
    for ( int i = 0; i < jsonArray.length(); i++ )  {
        if ( jsonArray.opt(i) instanceof JSONObject) {
            String mapJson = mapToJson((Map<String, Object>)jsonList.get(i));
            result.append(mapJson);
        }else if ( jsonArray.opt(i) instanceof JSONArray ) {
            String listJson = listToJson((List) jsonList.get(i));
            result.append(listJson);
        }else {
            result.append("\"").append(jsonArray.opt(i)).append("\"");
        }

        // 最後去掉 逗號
        if(i < jsonArray.length()-1){
            result.append(",");
        }
    }
    result.append("]");
    return result.toString();
}
相關文章
相關標籤/搜索