Search in sources :

Example 1 with JSONObject

use of cn.hutool.json.JSONObject in project hutool by looly.

the class JSONXMLSerializer method toXml.

/**
 * 转换JSONObject为XML
 *
 * @param object      JSON对象或数组
 * @param tagName     可选标签名称,名称为空时忽略标签
 * @param contentKeys 标识为内容的key,遇到此key直接解析内容而不增加对应名称标签
 * @return A string.
 * @throws JSONException JSON解析异常
 */
public static String toXml(Object object, String tagName, String... contentKeys) throws JSONException {
    if (null == object) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    if (object instanceof JSONObject) {
        // Emit <tagName>
        appendTag(sb, tagName, false);
        // Loop thru the keys.
        ((JSONObject) object).forEach((key, value) -> {
            if (ArrayUtil.isArray(value)) {
                value = new JSONArray(value);
            }
            // Emit content in body
            if (ArrayUtil.contains(contentKeys, key)) {
                if (value instanceof JSONArray) {
                    int i = 0;
                    for (Object val : (JSONArray) value) {
                        if (i > 0) {
                            sb.append(CharUtil.LF);
                        }
                        sb.append(EscapeUtil.escapeXml(val.toString()));
                        i++;
                    }
                } else {
                    sb.append(EscapeUtil.escapeXml(value.toString()));
                }
            // Emit an array of similar keys
            } else if (StrUtil.isEmptyIfStr(value)) {
                sb.append(wrapWithTag(null, key));
            } else if (value instanceof JSONArray) {
                for (Object val : (JSONArray) value) {
                    if (val instanceof JSONArray) {
                        sb.append(wrapWithTag(toXml(val), key));
                    } else {
                        sb.append(toXml(val, key));
                    }
                }
            } else {
                sb.append(toXml(value, key));
            }
        });
        // Emit the </tagname> close tag
        appendTag(sb, tagName, true);
        return sb.toString();
    }
    if (ArrayUtil.isArray(object)) {
        object = new JSONArray(object);
    }
    if (object instanceof JSONArray) {
        for (Object val : (JSONArray) object) {
            // XML does not have good support for arrays. If an array
            // appears in a place where XML is lacking, synthesize an
            // <array> element.
            sb.append(toXml(val, tagName == null ? "array" : tagName));
        }
        return sb.toString();
    }
    return wrapWithTag(EscapeUtil.escapeXml(object.toString()), tagName);
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray) JSONObject(cn.hutool.json.JSONObject)

Example 2 with JSONObject

use of cn.hutool.json.JSONObject in project hutool by looly.

the class XMLTest method escapeTest.

@Test
public void escapeTest() {
    String xml = "<a>•</a>";
    JSONObject jsonObject = XML.toJSONObject(xml);
    Assert.assertEquals("{\"a\":\"•\"}", jsonObject.toString());
    String xml2 = XML.toXml(JSONUtil.parseObj(jsonObject));
    Assert.assertEquals(xml, xml2);
}
Also used : JSONObject(cn.hutool.json.JSONObject) Test(org.junit.Test)

Example 3 with JSONObject

use of cn.hutool.json.JSONObject in project hutool by dromara.

the class JSONXMLSerializer method toXml.

/**
 * 转换JSONObject为XML
 *
 * @param object      JSON对象或数组
 * @param tagName     可选标签名称,名称为空时忽略标签
 * @param contentKeys 标识为内容的key,遇到此key直接解析内容而不增加对应名称标签
 * @return A string.
 * @throws JSONException JSON解析异常
 */
public static String toXml(Object object, String tagName, String... contentKeys) throws JSONException {
    if (null == object) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    if (object instanceof JSONObject) {
        // Emit <tagName>
        appendTag(sb, tagName, false);
        // Loop thru the keys.
        ((JSONObject) object).forEach((key, value) -> {
            if (ArrayUtil.isArray(value)) {
                value = new JSONArray(value);
            }
            // Emit content in body
            if (ArrayUtil.contains(contentKeys, key)) {
                if (value instanceof JSONArray) {
                    int i = 0;
                    for (Object val : (JSONArray) value) {
                        if (i > 0) {
                            sb.append(CharUtil.LF);
                        }
                        sb.append(EscapeUtil.escapeXml(val.toString()));
                        i++;
                    }
                } else {
                    sb.append(EscapeUtil.escapeXml(value.toString()));
                }
            // Emit an array of similar keys
            } else if (StrUtil.isEmptyIfStr(value)) {
                sb.append(wrapWithTag(null, key));
            } else if (value instanceof JSONArray) {
                for (Object val : (JSONArray) value) {
                    if (val instanceof JSONArray) {
                        sb.append(wrapWithTag(toXml(val), key));
                    } else {
                        sb.append(toXml(val, key));
                    }
                }
            } else {
                sb.append(toXml(value, key));
            }
        });
        // Emit the </tagname> close tag
        appendTag(sb, tagName, true);
        return sb.toString();
    }
    if (ArrayUtil.isArray(object)) {
        object = new JSONArray(object);
    }
    if (object instanceof JSONArray) {
        for (Object val : (JSONArray) object) {
            // XML does not have good support for arrays. If an array
            // appears in a place where XML is lacking, synthesize an
            // <array> element.
            sb.append(toXml(val, tagName == null ? "array" : tagName));
        }
        return sb.toString();
    }
    return wrapWithTag(EscapeUtil.escapeXml(object.toString()), tagName);
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONArray(cn.hutool.json.JSONArray) JSONObject(cn.hutool.json.JSONObject)

Example 4 with JSONObject

use of cn.hutool.json.JSONObject in project hutool by looly.

the class JSONXMLParser method parse.

/**
 * Scan the content following the named tag, attaching it to the context.
 *
 * @param x       The XMLTokener containing the source string.
 * @param context The JSONObject that will include the new material.
 * @param name    The tag name.
 * @return true if the close tag is processed.
 * @throws JSONException JSON异常
 */
private static boolean parse(XMLTokener x, JSONObject context, String name, boolean keepStrings) throws JSONException {
    char c;
    int i;
    JSONObject jsonobject;
    String string;
    String tagName;
    Object token;
    token = x.nextToken();
    if (token == XML.BANG) {
        c = x.next();
        if (c == '-') {
            if (x.next() == '-') {
                x.skipPast("-->");
                return false;
            }
            x.back();
        } else if (c == '[') {
            token = x.nextToken();
            if ("CDATA".equals(token)) {
                if (x.next() == '[') {
                    string = x.nextCDATA();
                    if (string.length() > 0) {
                        context.accumulate("content", string);
                    }
                    return false;
                }
            }
            throw x.syntaxError("Expected 'CDATA['");
        }
        i = 1;
        do {
            token = x.nextMeta();
            if (token == null) {
                throw x.syntaxError("Missing '>' after '<!'.");
            } else if (token == XML.LT) {
                i += 1;
            } else if (token == XML.GT) {
                i -= 1;
            }
        } while (i > 0);
        return false;
    } else if (token == XML.QUEST) {
        // <?
        x.skipPast("?>");
        return false;
    } else if (token == XML.SLASH) {
        // Close tag </
        token = x.nextToken();
        if (name == null) {
            throw x.syntaxError("Mismatched close tag " + token);
        }
        if (!token.equals(name)) {
            throw x.syntaxError("Mismatched " + name + " and " + token);
        }
        if (x.nextToken() != XML.GT) {
            throw x.syntaxError("Misshaped close tag");
        }
        return true;
    } else if (token instanceof Character) {
        throw x.syntaxError("Misshaped tag");
    // Open tag <
    } else {
        tagName = (String) token;
        token = null;
        jsonobject = new JSONObject();
        for (; ; ) {
            if (token == null) {
                token = x.nextToken();
            }
            // attribute = value
            if (token instanceof String) {
                string = (String) token;
                token = x.nextToken();
                if (token == XML.EQ) {
                    token = x.nextToken();
                    if (!(token instanceof String)) {
                        throw x.syntaxError("Missing value");
                    }
                    jsonobject.accumulate(string, keepStrings ? token : InternalJSONUtil.stringToValue((String) token));
                    token = null;
                } else {
                    jsonobject.accumulate(string, "");
                }
            } else if (token == XML.SLASH) {
                // Empty tag <.../>
                if (x.nextToken() != XML.GT) {
                    throw x.syntaxError("Misshaped tag");
                }
                if (jsonobject.size() > 0) {
                    context.accumulate(tagName, jsonobject);
                } else {
                    context.accumulate(tagName, "");
                }
                return false;
            } else if (token == XML.GT) {
                // Content, between <...> and </...>
                for (; ; ) {
                    token = x.nextContent();
                    if (token == null) {
                        if (tagName != null) {
                            throw x.syntaxError("Unclosed tag " + tagName);
                        }
                        return false;
                    } else if (token instanceof String) {
                        string = (String) token;
                        if (string.length() > 0) {
                            jsonobject.accumulate("content", keepStrings ? token : InternalJSONUtil.stringToValue(string));
                        }
                    } else if (token == XML.LT) {
                        // Nested element
                        if (parse(x, jsonobject, tagName, keepStrings)) {
                            if (jsonobject.size() == 0) {
                                context.accumulate(tagName, "");
                            } else if (jsonobject.size() == 1 && jsonobject.get("content") != null) {
                                context.accumulate(tagName, jsonobject.get("content"));
                            } else {
                                context.accumulate(tagName, jsonobject);
                            }
                            return false;
                        }
                    }
                }
            } else {
                throw x.syntaxError("Misshaped tag");
            }
        }
    }
}
Also used : JSONObject(cn.hutool.json.JSONObject) JSONObject(cn.hutool.json.JSONObject)

Example 5 with JSONObject

use of cn.hutool.json.JSONObject in project hutool by looly.

the class XMLTest method toXmlTest.

@Test
public void toXmlTest() {
    final JSONObject put = JSONUtil.createObj().set("aaa", "你好").set("键2", "test");
    final String s = JSONUtil.toXmlStr(put);
    Assert.assertThat(s, CoreMatchers.anyOf(CoreMatchers.is("<aaa>你好</aaa><键2>test</键2>"), CoreMatchers.is("<键2>test</键2><aaa>你好</aaa>")));
}
Also used : JSONObject(cn.hutool.json.JSONObject) Test(org.junit.Test)

Aggregations

JSONObject (cn.hutool.json.JSONObject)12 Test (org.junit.Test)6 JSONArray (cn.hutool.json.JSONArray)3 Page (com.ruiyun.jvppeteer.core.page.Page)2 SneakyThrows (lombok.SneakyThrows)2 CollUtil (cn.hutool.core.collection.CollUtil)1 DateTime (cn.hutool.core.date.DateTime)1 DateUtil (cn.hutool.core.date.DateUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 Retry (com.hsn.epic4j.aop.Retry)1 Item (com.hsn.epic4j.bean.Item)1 SelectItem (com.hsn.epic4j.bean.SelectItem)1 EpicConfig (com.hsn.epic4j.config.EpicConfig)1 ItemException (com.hsn.epic4j.exception.ItemException)1 PermissionException (com.hsn.epic4j.exception.PermissionException)1 TimeException (com.hsn.epic4j.exception.TimeException)1 PageUtil (com.hsn.epic4j.util.PageUtil)1 Constant (com.ruiyun.jvppeteer.core.Constant)1 Puppeteer (com.ruiyun.jvppeteer.core.Puppeteer)1 Browser (com.ruiyun.jvppeteer.core.browser.Browser)1