Java 类net.sf.json.xml.XMLSerializer 实例源码

项目:GitHub    文件:JSONLibXmlTest.java   
public void test_xml() throws Exception {
    XMLSerializer xmlSerializer = new XMLSerializer();

    JSONObject json = new JSONObject();
    json.put("id", 123);
    json.put("name", "jobs");
    json.put("flag", true);

    JSONArray items = new JSONArray();
    items.add("x");
    items.add(234);
    items.add(false);
    json.put("items", items);

    String text = xmlSerializer.write(json);
    System.out.println(text);
}
项目:appBack    文件:queryCarXmlServlet.java   
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//      response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");// 解决乱码问题
        request.setCharacterEncoding("UTF-8");
            PrintWriter out= response.getWriter();
            String hphm  = new String(request.getParameter("carno").getBytes("ISO-8859-1"),"utf-8");//解决get连接中文乱码
            String classno=request.getParameter("classno");
            String engineno=request.getParameter("engineno");
            String cityid=request.getParameter("cityid");
            String cartype=request.getParameter("cartype");
            String carInfo = "{hphm="+hphm+"&classno="+classno+"&engineno="+engineno+"&city_id="+cityid+"&car_type="+cartype+"}";
            String sb =WeizhangTexst. getWeizhangInfoPost(carInfo);
            JSONObject jsonObject = JSONObject.fromObject(sb);  
            System.out.println(hphm);
            String xmlstr = new XMLSerializer().write(jsonObject); 
             out.print(xmlstr);
    }
项目:ArbitraryGen    文件:PsychicAGEngine.java   
private void dealPsychicDefine(AGContext core, Map<String, ArbitraryGenProcessor> processors, JSONArray fileArray) {
    if (fileArray == null || fileArray.isEmpty()) {
        Log.i(TAG, "scan out psychic define file list is nil.");
        return;
    }
    ArbitraryGenProcessor psychicProcessor = processors.get("psychic-processor");
    for (int i = 0; i < fileArray.size(); i++) {
        String path = fileArray.optString(i);
        if (Util.isNullOrNil(path)) {
            Log.i(TAG, "file path is null or nil.");
            continue;
        }
        XMLSerializer ss = new XMLSerializer();
        ss.setTypeHintsEnabled(false);
        ss.setTypeHintsCompatibility(false);
        Log.i(TAG, "process src : %s", path);
        String rawContent = FileOperation.read(path);
        JSONObject json = (JSONObject) ss.read(RuntimeContextHelper.replace(rawContent));
        if (json == null) {
            Log.i(TAG, "read JSONObject from XML file(%s) failed.", path);
            continue;
        }
        json = JSONArgsUtils.validKey(json);
        psychicProcessor.exec(core, processors, json);
    }
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * 将xml中列表信息转化对象数组
 * 
 * @param xml
 * @param beanClass
 * @return
 */
public static Object[] xml2ArrayForObject(String xml, Class beanClass) {

    // 设置root为数组
    xml = setXmlRootAttrToArray(xml);
    XMLSerializer xmlSer = new XMLSerializer();
    JSON jsonArr = xmlSer.read(xml);
    Object[] objArr = new Object[jsonArr.size()];

    for (int i = 0; i < jsonArr.size(); i++) {
        objArr[i] = JSONObject.toBean(
                ((JSONArray) jsonArr).getJSONObject(i), beanClass);
    }

    return objArr;
}
项目:easyrec_major    文件:AbstractApiTest.java   
public JSONObject makeAPIRequest(String apiFunction, @Nullable MultivaluedMap<String, String> params) {
    ClientResponse clientResponse = makeAPIResource(apiFunction, params).get(ClientResponse.class);

    log.info(clientResponse.getLocation());

    String response = clientResponse.getEntity(String.class);

    System.out.println(response);
    log.info("response: " + response);

    if (!method.equals("json/")) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(response);

        System.out.println(json);

        return JSONObject.fromObject(json);
    } else
        return JSONObject.fromObject(response);
}
项目:easyrec-PoC    文件:AbstractApiTest.java   
public JSONObject makeAPIRequest(String apiFunction, @Nullable MultivaluedMap<String, String> params) {
    ClientResponse clientResponse = makeAPIResource(apiFunction, params).get(ClientResponse.class);

    log.info(clientResponse.getLocation());

    String response = clientResponse.getEntity(String.class);

    System.out.println(response);
    log.info("response: " + response);

    if (!method.equals("json/")) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(response);

        System.out.println(json);

        return JSONObject.fromObject(json);
    } else
        return JSONObject.fromObject(response);
}
项目:easyrec    文件:AbstractApiTest.java   
public JSONObject makeAPIRequest(String apiFunction, @Nullable MultivaluedMap<String, String> params) {
    ClientResponse clientResponse = makeAPIResource(apiFunction, params).get(ClientResponse.class);

    log.info(clientResponse.getLocation());

    String response = clientResponse.getEntity(String.class);

    System.out.println(response);
    log.info("response: " + response);

    if (!method.equals("json/")) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(response);

        System.out.println(json);

        return JSONObject.fromObject(json);
    } else
        return JSONObject.fromObject(response);
}
项目:jay-lang    文件:Weather.java   
@JayMd(value = { "天气", "weather" })
@JayDoc("Query the weather in China mainland")
public static void weather(JayFunc func) throws UnsupportedEncodingException {
    JayArgs arg = func.getArgs();
    String city = arg.getArg(0, "上海");
    String day = arg.getArg(1, "0");
    if(arg.getArgAmount() >= 2 && DAYS.containsKey(day)) {
        day = DAYS.getString(day);
    }
    city = URLEncoder.encode(city,"gb2312");
    String url = SINA_WEATHER_URL.replace("${city}", city).replace("${day}", day);
    String xml = HttpUtils.getString(url);
    if(StringUtils.isEmpty(xml)) {
        func.setResult(JSONObject.parse("<msg>Not found!</msg>"));
        return;
    }
    String json = new XMLSerializer().read(xml).toString();
    Object result = JSONObject.parse(json);
    if(result instanceof JSONArray) {
        JSONArray arr = (JSONArray) result;
        if(arr.isEmpty()) {
            func.setResult(JSONObject.parse("<msg>Not found!</msg>"));
            return;
        }
        func.setResult(arr.get(0));
    } else {
        func.setResult(result);
    }
}
项目:helicalinsight    文件:XmlOperation.java   
public String convertJsonToXml(JSONArray jsonArray) {
    XMLSerializer serializer = new XMLSerializer();
    serializer.setTypeHintsEnabled(false);
    serializer.setForceTopLevelObject(true);
    serializer.setElementName("Schedule");
    serializer.setRootName("Schedules");
    return serializer.write(jsonArray);
}
项目:helicalinsight    文件:XmlOperation.java   
public JSON convertXmlStringToJSon(String xmlData) {
    JSON json;
    XMLSerializer xmlSerializer = new XMLSerializer();
    xmlSerializer.setForceTopLevelObject(false);
    json = xmlSerializer.read(xmlData);
    return json;
}
项目:helicalinsight    文件:XmlOperation.java   
public String convertJsonToXml(JSONObject jsonObject) {
    XMLSerializer serializer = new XMLSerializer();
    serializer.setTypeHintsEnabled(false);
    serializer.setForceTopLevelObject(true);
    serializer.setElementName("Schedule");
    serializer.setRootName("Schedules");
    String result = serializer.write(jsonObject);
    logger.debug("result" + result);
    return result;
}
项目:ArbitraryGen    文件:ParseXmlProcessor.java   
@Override
public JSONObject exec(AGContext context, Map<String, ArbitraryGenProcessor> processors, JSONObject args) {
    String name = args.optString("_name");
    if (Util.isNullOrNil(name)) {
        Log.i(TAG, "exec failed, name is null.");
        return null;
    }
    JSONObject result = context.execProcess(processors, "parse-rule", args);
    if (result == null) {
        Log.i(TAG, "parse rule result is null.");
        return null;
    }
    JSONArray fileArray = result.optJSONArray("fileArray");
    if (fileArray == null) {
        Log.i(TAG, "file array is null.");
        return null;
    }
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < fileArray.size(); i++) {
        String path = fileArray.optString(i);
        XMLSerializer ss = new XMLSerializer();
        ss.setTypeHintsEnabled(false);
        ss.setTypeHintsCompatibility(false);
        Log.i(TAG, "process parse xml file : %s", path);
        JSONObject jsonObject = (JSONObject) ss.read(RuntimeContextHelper.replace(FileOperation.read(path)));
        if (jsonObject != null) {
            jsonObject = JSONArgsUtils.validKey(jsonObject);
            jsonArray.add(jsonObject);
        }
    }
    JSONObject r = new JSONObject();
    r.put(name, jsonArray);
    return r;
}
项目:ArbitraryGen    文件:JsTemplateProcessor.java   
@Override
public void process(String src, String destPath) {
    if (src == null || destPath == null) {
        throw new RuntimeException(String.format("src file(%s) or dest path(%s) is null.", src, destPath));
    }
    File file = new File(src);
    if (!file.exists() || !file.isFile()) {
        throw new RuntimeException(String.format("src file(%s) do not exist.", src));
    }

    XMLSerializer ss = new XMLSerializer();
    ss.setTypeHintsEnabled(false);
    ss.setTypeHintsCompatibility(false);
    Log.i(TAG, "process src : %s", src);
    JSONObject json = (JSONObject) ss.read(RuntimeContextHelper.replace(FileOperation.read(src)));

    TaskInfo info = new TaskInfo();
    info.script = mCoreScript;
    info.destPath = destPath;
    info.templateLibs = mTemplateCfg.getTemplateLibs();
    info.templateSuffix = Util.nullAsNil(Util.getSuffix(src));

    for (PsychicGenerator worker : mWorkers) {
        if (worker instanceof AGPsychicWorker) {
            if (info.templateSuffix.equalsIgnoreCase(((AGPsychicWorker) worker).getSupportSuffix())) {
                worker.genCode(mScriptEngine, json, info);
                continue;
            }
        }
        if (worker instanceof AGPyroWorker) {
            if (isSupportSuffix((AGPyroWorker) worker, info.templateSuffix)) {
                worker.genCode(mScriptEngine, json, info);
                continue;
            }
        }
        // Add more case here
    }
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * 将简单xml中信息转化Map<br>
 * 
 * @param xml
 * @return
 */
public static Map xml2Map(String xml) {
    //案例:
    //<object><id type="string">77777</id><userName type="string">chenyc</userName></object>
    XMLSerializer xmlSer = new XMLSerializer();
    JSON json = xmlSer.read(xml);

    return (JSONObject)json;
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * 将xml中列表信息转化对象数组
 * 
 * @param xml
 * @return
 */
public static Object[] xml2ArrayForMap(String xml) {

    // 设置root为数组
    xml = setXmlRootAttrToArray(xml);
    XMLSerializer xmlSer = new XMLSerializer();
    JSON json = xmlSer.read(xml);
    if(json.isArray()){
        return ((JSONArray) json).toArray();
    }
    return new Object[]{json};
}
项目:APICloud-Studio    文件:Feature.java   
public static String ConvertXMLtoJSON(String xml)  {  
    XMLSerializer xmlSerializer = new XMLSerializer();  
    JSON json =null;

       json = xmlSerializer.read(xml);  
    return json.toString(1);  
}
项目:OpsDev    文件:SocketClient.java   
/**
* 解析告警信息
* @param str
* @return
*/
public String currentAlarmMessage(String str){
    String message = "";
    JSONObject object = JSONObject.fromObject(str);
    XMLSerializer xmlSerializer = new XMLSerializer();
    String xml = xmlSerializer.write(JSONSerializer.toJSON(object));
    String xml2 =xml.replace("<o>","").replace("</o>","").replace("<e class=\"object\">","").replace("</e>",""); 
    Alarm alarm = new Alarm(xml2);
    message = alarm.getOpsMessage3();
    return message;
}
项目:ankush    文件:Graph.java   
private JSON exeExportCommand(String command) throws Exception {
    try {
        // puting json in result.
        return new XMLSerializer().read(exeCommand(command).replaceAll(
                "NaN", "0"));
    } catch (Exception e) {
        logger.error("Could not run export command." + e.getMessage());
        throw new AnkushException("Coud not run export command.");
    }
}
项目:jw    文件:XmlConverUtil.java   
public static String xmltoJson(String xml) {  
    XMLSerializer xmlSerializer = new XMLSerializer();  
    return xmlSerializer.read(xml).toString();  
}
项目:Camel    文件:XmlJsonDataFormat.java   
@Override
protected void doStart() throws Exception {
    serializer = new XMLSerializer();

    if (forceTopLevelObject != null) {
        serializer.setForceTopLevelObject(forceTopLevelObject);
    }

    if (namespaceLenient != null) {
        serializer.setNamespaceLenient(namespaceLenient);
    }

    if (namespaceMappings != null) {
        for (NamespacesPerElementMapping nsMapping : namespaceMappings) {
            for (Entry<String, String> entry : nsMapping.namespaces.entrySet()) {
                // prefix, URI, elementName (which can be null or empty
                // string, in which case the
                // mapping is added to the root element
                serializer.addNamespace(entry.getKey(), entry.getValue(), nsMapping.element);
            }
        }
    }

    if (rootName != null) {
        serializer.setRootName(rootName);
    }

    if (elementName != null) {
        serializer.setElementName(elementName);
    }

    if (arrayName != null) {
        serializer.setArrayName(arrayName);
    }

    if (expandableProperties != null && expandableProperties.size() != 0) {
        serializer.setExpandableProperties(expandableProperties.toArray(new String[expandableProperties.size()]));
    }

    if (skipWhitespace != null) {
        serializer.setSkipWhitespace(skipWhitespace);
    }

    if (trimSpaces != null) {
        serializer.setTrimSpaces(trimSpaces);
    }

    if (skipNamespaces != null) {
        serializer.setSkipNamespaces(skipNamespaces);
    }

    if (removeNamespacePrefixes != null) {
        serializer.setRemoveNamespacePrefixFromElements(removeNamespacePrefixes);
    }

    if (typeHints == TypeHintsEnum.YES || typeHints == TypeHintsEnum.WITH_PREFIX) {
        serializer.setTypeHintsEnabled(true);
        if (typeHints == TypeHintsEnum.WITH_PREFIX) {
            serializer.setTypeHintsCompatibility(false);
        } else {
            serializer.setTypeHintsCompatibility(true);
        }
    } else {
        serializer.setTypeHintsEnabled(false);
        serializer.setTypeHintsCompatibility(false);
    }
}
项目:Camel    文件:XmlJsonDataFormat.java   
public XMLSerializer getSerializer() {
    return serializer;
}
项目:ankush    文件:NodeGraph.java   
/**
     * Method to extract json from the rrd file.
     * hostNames = GangliaUtils.getGangliaHostNames(hostname, username,
//              password, privateKey);
     * @param startTime
     *            the start time
     * @param hostName
     *            the hostName
     * @return the map
     * @throws Exception
     *             the exception
     */
    public Map extractRRD(StartTime startTime, String hostName) throws Exception {

        Map result = new HashMap();
        // rrd director for the given ip address.
        String rrdDir = rrdsDirectory + clusterName + "/" + hostName + "/";

        // making connection.
        SSHConnection connection = new SSHConnection(this.hostname,
                this.username, this.authInfo, this.authUsingPassword);

        if (connection.isConnected()) {

            // json creation command using the rrdtool.
            StringBuilder command = new StringBuilder();
            command.append("cd " + rrdDir).append(";rrdtool xport ")
                    .append(timeMap.get(startTime.ordinal()))
                    .append("DEF:cn=cpu_num.rrd:sum:AVERAGE ")
                    .append("DEF:ci=cpu_idle.rrd:sum:AVERAGE ")
                    .append("DEF:mt=mem_total.rrd:sum:AVERAGE ")
                    .append("DEF:mf=mem_free.rrd:sum:AVERAGE ")
                    .append("DEF:mb=mem_buffers.rrd:sum:AVERAGE ")
                    .append("DEF:mc=mem_cached.rrd:sum:AVERAGE ")
                    .append("DEF:ms=mem_shared.rrd:sum:AVERAGE ")
                    .append("CDEF:mu=mt,ms,-,mf,-,mc,-,mb,- ")
                    .append("CDEF:mem=100,mu,*,mt,/ ")
                    .append("CDEF:cpu=100,ci,- ")
                    .append("XPORT:cpu:\"CPU %\" ")
                    .append("XPORT:mem:\"Memory %\" ");

            /* Executing the command. */
            if (connection.exec(command.toString())) {
                String output = connection.getOutput();
                if (output == null) {
                    throw new Exception(COULD_NOT_FETCH_DATA_MSG);
                }

                // puting json in result.
                result.put("json",
                        new XMLSerializer().read(output.replaceAll("NaN", "0")));
            } else {
                throw new Exception(
                        COULD_NOT_EXECUTE_COMMAND_MSG);
            }
        }
        return result;
    }
项目:ankush    文件:LiveGraph.java   
/**
 * Method to provide Data from cluster memory, cpu, load and network data
 * for given time period.
 * 
 * @param startTime
 * @param pattern
 * @return
 * @throws Exception
 */
public Map fetchGraphJson(StartTime startTime, String type)
        throws Exception {
    // output.
    Map result = new HashMap();
    // rrd cluster directory.
    String clusterRrdDir = FileNameUtils.convertToValidPath(rrdsDirectory
            + clusterName + "/__SummaryInfo__");
    // making connection.
    SSHConnection connection = new SSHConnection(this.hostname,
            this.username, this.authInfo, this.authUsingPassword);

    if (connection.isConnected()) {

        // json creation command using the rrdtool.
        StringBuilder command = new StringBuilder();
        command.append("cd " + clusterRrdDir).append(";rrdtool xport ")
                .append(timeMap.get(startTime.ordinal()));

        String unit = "%";
        // cpu graphs
        if (type.equalsIgnoreCase(Constant.Graph.Type.cpu.toString())) {
            command.append(getClusterCpu(false));
            // memory graphs
        } else if (type.equalsIgnoreCase(Constant.Graph.Type.memory
                .toString())) {
            command.append(getClusterMemory(false));
            // network graphs.
        } else if (type.equalsIgnoreCase(Constant.Graph.Type.network
                .toString())) {
            unit = "MB/s";
            command.append(getClusterNetwork(false));
            // load graphs.
        } else if (type.equalsIgnoreCase(Constant.Graph.Type.load
                .toString())) {
            command.append(getClusterLoad(false));
        } else {
            return result;
        }

        logger.debug(command.toString());

        /* Executing the command. */
        if (connection.exec(command.toString())) {
            String output = connection.getOutput();
            if (output == null) {
                throw new Exception(COULD_NOT_FETCH_DATA_MSG);
            } else {
                // puting json in result.
                Map map = (Map) new XMLSerializer().read(output.replaceAll(
                        "NaN", "0"));
                map.put("unit", unit);
                result.put("json", map);
            }
        } else {
            throw new Exception(COULD_NOT_EXECUTE_COMMAND_MSG);
        }
    }
    return result;
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * xml转化成JSON
 * 
 * @param xml
 *            xml字符串
 * @param isRootArray
 *            根节点是否为数组,isRootArray=true时设置根节点为数组;<br>
 *            否则自动判断,可能为Array(当根节点的子元素>1时 root为Array);<br>
 *            也有可能为Object(当根节点的子元素=1时 root为Object).
 * 
 * @return
 */
public static String xml2JSON(String xml, boolean isRootArray) {
    Element root;
    Document doc;
    // 设置root为数组
    if (isRootArray) {
        xml = setXmlRootAttrToArray(xml);
    }
    XMLSerializer xmlSer = new XMLSerializer();
    return xmlSer.read(xml).toString();
}
项目:xml2json    文件:XmlExercise.java   
/**
 * 将xml字符串<STRONG>转换</STRONG>为JSON字符串
 *
 * @param xmlString
 *            xml字符串
 * @return JSON<STRONG>对象</STRONG>
 */
public static String xml2json(String xmlString) {
    XMLSerializer xmlSerializer = new XMLSerializer();
    JSON json = xmlSerializer.read(xmlString);
    return json.toString(1);
}
项目:xml2json    文件:XmlExercise.java   
/**
 * JSON(数组)字符串<STRONG>转换</STRONG>成XML字符串
 *
 * @param jsonString
 * @return
 */
public static String json2xml(String jsonString) {
    XMLSerializer xmlSerializer = new XMLSerializer();
    return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
    // return xmlSerializer.write(JSONArray.fromObject(jsonString));//这种方式只支持JSON数组
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * @param pojo
 * @return
 * @see #pojo2XML(Object, XMLSerializer)
 */
public static String pojo2XML(Object pojo) {
    return pojo2XML(pojo, new XMLSerializer());
}
项目:nbone    文件:JSONXOperUtils.java   
/**
 * @param json
 * @return
 * @see #json2XML(String, XMLSerializer)
 */
public static String json2XML(String json) {

    return json2XML(json, new XMLSerializer());
}