// Converts XML to JSON
function XMLtoJSON() {
  
   var me = this; // stores the object instantce

   // gets the content of an xml file and returns it in
   me.fromFile = function(xml, rstr) {
      // Cretes a instantce of XMLHttpRequest object
      var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest()
            : new ActiveXObject("Microsoft.XMLHTTP");
      // sets and sends the request for calling "xml"
      xhttp.open("GET", xml, false);
      xhttp.send(null);

      // gets the JSON string
      var json_str = jsontoStr(setJsonObj(xhttp.responseXML));

      // sets and returns the JSON object, if "rstr" undefined (not passed),
      // else, returns JSON string
      return (typeof (rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
   }

   // returns XML DOM from string with xml content
   me.fromStr = function(xml, rstr) {
      // for non IE browsers
      if (window.DOMParser) {
         var getxml = new DOMParser();
         var xmlDoc = getxml.parseFromString(xml, "text/xml");
      } else {
         // for Internet Explorer
         var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
         xmlDoc.async = "false";
      }

      // gets the JSON string
      var json_str = jsontoStr(setJsonObj(xmlDoc));

      // sets and returns the JSON object, if "rstr" undefined (not passed),
      // else, returns JSON string
      return (typeof (rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
   }

   // receives XML DOM object, returns converted JSON object
   var setJsonObj = function(xml) {
      var js_obj = {};
      if (xml.nodeType == 1) {
         if (xml.attributes.length > 0) {
            js_obj["@attributes"] = {};
            for ( var j = 0; j < xml.attributes.length; j++) {
               var attribute = xml.attributes.item(j);
               js_obj["@attributes"][attribute.nodeName] = attribute.value;
            }
         }
      } else if (xml.nodeType == 3) {
         js_obj = xml.nodeValue;
      }
      if (xml.hasChildNodes()) {
         for ( var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof (js_obj[nodeName]) == "undefined") {
               js_obj[nodeName] = setJsonObj(item);
            } else {
               if (typeof (js_obj[nodeName].push) == "undefined") {
                  var old = js_obj[nodeName];
                  js_obj[nodeName] = [];
                  js_obj[nodeName].push(old);
               }
               js_obj[nodeName].push(setJsonObj(item));
            }
         }
      }
      return js_obj;
   }

   // converts JSON object to string (human readablle).
   // Removes '    \r\n', rows with multiples '""', multiple empty rows, ' "",',
   // and " ",; replace empty [] with ""
   var jsontoStr = function(js_obj) {
      var rejsn = JSON.stringify(js_obj, undefined, 2).replace(
            /(\    |\\r|\\n)/g, '').replace(/"",[\n    \r\s]+""[,]*/g, '')
            .replace(/(\n[    \s\r]*\n)/g, '').replace(
                  /[\s    ]{2,}""[,]{0,1}/g, '').replace(
                  /"[\s    ]{1,}"[,]{0,1}/g, '').replace(/\[[    \s]*\]/g,
                  '""');
      return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn
            : 'Invalid XML format';
   }
};

// creates object instantce of XMLtoJSON

var xml2json = new XMLtoJSON();


'프로그래밍 > Javascript' 카테고리의 다른 글

특수문자 및 공백 제거  (0) 2019.03.07
String 관련 utils  (0) 2019.03.07
ArrayUtils  (0) 2019.03.07
[javascript] Object push를 이용한 Validation Check  (0) 2019.03.07
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*    일반문자열 유틸.
*
* @author someone
* @version 1.0.0
*/
public class JsonUtil {
    /**
     * 로그 출력.
     */
    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(JsonUtil.class);
    /**
     * Map을 jsonString으로 변환한다.
     *
     * @param map Map<String, Object>.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static JSONObject getJsonStringFromMap( Map<String, Object> map ) {
        JSONObject json = new JSONObject();
        for( Map.Entry<String, Object> entry : map.entrySet() ) {
            String key = entry.getKey();
            Object value = entry.getValue();
            json.put(key, value);
        }
        
        return json;
    }
    
    /**
     * List<Map>을 json으로 변환한다.
     *
     * @param list List<Map<String, Object>>.
     * @return JSONArray.
     */
    @SuppressWarnings("unchecked")
    public static JSONArray getJsonArrayFromList( List<Map<String, Object>> list ) {
        JSONArray jsonArray = new JSONArray();
        for( Map<String, Object> map : list ) {
            jsonArray.add( getJsonStringFromMap( map ) );
        }
        
        return jsonArray;
    }
    
    /**
     * List<Map>을 jsonString으로 변환한다.
     *
     * @param list List<Map<String, Object>>.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static String getJsonStringFromList( List<Map<String, Object>> list ) {
        JSONArray jsonArray = new JSONArray();
        for( Map<String, Object> map : list ) {
            jsonArray.add( getJsonStringFromMap( map ) );
        }
        
        return jsonArray.toJSONString();
    }
    /**
     * JsonObject를 Map<String, String>으로 변환한다.
     *
     * @param jsonObj JSONObject.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getMapFromJsonObject( JSONObject jsonObj ) {
        Map<String, Object> map = null;
        
        try {
            
            map = new ObjectMapper().readValue(jsonObj.toJSONString(), Map.class) ;
            
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * JsonArray를 List<Map<String, String>>으로 변환한다.
     *
     * @param jsonArray JSONArray.
     * @return List<Map<String, Object>>.
     */
    public static List<Map<String, Object>> getListMapFromJsonArray( JSONArray jsonArray ) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        
        if( jsonArray != null )
        {
            int jsonSize = jsonArray.size();
            for( int i = 0; i < jsonSize; i++ )
            {
                Map<String, Object> map = JsonUtil.getMapFromJsonObject( ( JSONObject ) jsonArray.get(i) );
                list.add( map );
            }
        }
        
        return list;
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

java 컬렉션 종류  (0) 2019.03.07
RSA암호화 key생성 암호화 복호화  (0) 2019.03.07
RSA암호화 sample  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07

+ Recent posts