Skip to content

Commit 6101d54

Browse files
committed
实现 json to xml | xml to json
1 parent c9acb2b commit 6101d54

File tree

9 files changed

+879
-40
lines changed

9 files changed

+879
-40
lines changed

src/ws/http/test/TestCase.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ public void testJson()
3131
// logger.info( JSON.NULL.toString() );
3232
String json = "{\"account_id\":121,\"channel\":{\"a\":[6,6,\"jj\"]},\"domain\":\"183.131.145.124\",\"port\":\"80\",\"request_id\":\"e54af3f3-d915-4524-8805-3108d78a2220\",\"request_time\":\"1473833813956\",\"timestamp\":1474251393,\"sign\":\"6905d6e800b8bfed60ca02efbe404abb\"}";
3333
jsonobj = JSON.parseJSON(json);
34-
35-
// System.out.println(XML.toXML(jsonobj));
34+
//
35+
System.out.println(XML.toXML(json));
36+
//// System.out.println(XML.toXML(jsonobj));
3637

3738
// System.out.println(jsonobj.asObject().get("channel"));
3839
//
@@ -45,7 +46,9 @@ public void testJson()
4546
//
4647
// jsonobj = JSON.parseJSONFile("C:/tmptt/postmanv1.json", false);
4748
// System.out.println(XML.toXML(jsonobj, "doc"));
48-
49+
HashMap<?, ?> xmlobj = XML.parseXMLFile("C:/tmptt/postmanv1.xml", false);
50+
System.out.println();
51+
System.out.println();
4952
ArrayList<Object> b = new ArrayList<>();
5053
b.add("aaa");
5154
b.add("aaa");
@@ -59,7 +62,7 @@ public void testJson()
5962
a.put("ssd6", b);
6063
a.put("ssd7", "ddd");
6164
// System.out.println(JSON.toJSON(a));
62-
System.out.println( XML.toXML(a, "doc"));
65+
// System.out.println( XML.toXML(a, "doc"));
6366
// logger.info(jsonobj.toString());
6467
// System.out.println(JSON.query(jsonobj, "id").asString());
6568
// System.out.println(JSON.query(jsonobj, "description").asString());

src/ws/http/tools/File.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ public static final String readFromURL(String url) {
3333
}
3434
return null;
3535
}
36+
37+
public static final String readFromResource(String resource) {
38+
return read(File.class.getResourceAsStream(resource));
39+
}
3640

3741
private static final String read(InputStream is) {
3842
try {

src/ws/http/tools/JScriptEngine.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package ws.http.tools;
2+
3+
import javax.script.Invocable;
4+
import javax.script.ScriptEngine;
5+
import javax.script.ScriptEngineManager;
6+
import javax.script.ScriptException;
7+
8+
/**
9+
* JScriptEngine
10+
*
11+
* @see http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
12+
* @see http://codereview.stackexchange.com/questions/90272/java-json-parsing-with-the-nashorn-api
13+
*/
14+
public class JScriptEngine {
15+
16+
private ScriptEngineManager engineManager;
17+
private ScriptEngine engine;
18+
19+
private static JScriptEngine instance = null;
20+
21+
private JScriptEngine()
22+
{
23+
this.engineManager = new ScriptEngineManager();
24+
this.engine = this.engineManager.getEngineByName("nashorn");
25+
if (this.engine == null)
26+
{
27+
this.engine = this.engineManager.getEngineByExtension("js");
28+
}
29+
}
30+
31+
public static JScriptEngine getInstance()
32+
{
33+
if (instance == null)
34+
{
35+
instance = new JScriptEngine();
36+
}
37+
38+
return instance;
39+
}
40+
41+
public Object require(String path) throws ScriptException
42+
{
43+
if (null != path)
44+
{
45+
String script = File.readFromPath(path);
46+
if (null != script)
47+
{
48+
return engine.eval(script);
49+
}
50+
}
51+
return null;
52+
}
53+
54+
public Object eval(String script) throws ScriptException
55+
{
56+
return engine.eval(script);
57+
}
58+
59+
public Object call(String objName, String method, Object... args) throws NoSuchMethodException, ScriptException
60+
{
61+
Invocable invocable = (Invocable) engine;
62+
Object obj = engine.get(objName);
63+
if (obj != null) return invocable.invokeMethod(obj, method, args);
64+
return null;
65+
}
66+
67+
public Object call(String function, Object... args) throws NoSuchMethodException, ScriptException
68+
{
69+
Invocable invocable = (Invocable) engine;
70+
return invocable.invokeFunction(function, args);
71+
}
72+
73+
public ScriptEngine getEngine() {
74+
return engine;
75+
}
76+
77+
}

src/ws/http/tools/json/JSON.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.io.Reader;
2626

2727
import ws.http.tools.File;
28+
import ws.http.tools.xml.XML;
2829

2930
/**
3031
* This class serves as the entry point to the minimal-json API.
@@ -376,6 +377,18 @@ public static String toJSON(Object obj) {
376377
if (obj instanceof JsonValue) return obj.toString();
377378
return ToJson.toJSON(obj);
378379
}
380+
381+
/**
382+
* Convert a json string into a xml.
383+
*
384+
* @param json
385+
* @return
386+
*/
387+
public static String toXML(String json, String tag)
388+
{
389+
JsonValue jv = parseJSON(json);
390+
return XML.toXML(jv, tag);
391+
}
379392

380393
private static String cutOffPointZero(String string) {
381394
if (string.endsWith(".0")) {

src/ws/http/tools/xml/XML.java

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.io.ByteArrayInputStream;
44
import java.io.ByteArrayOutputStream;
5+
import java.util.HashMap;
56
import java.util.Iterator;
67

78
import javax.xml.transform.OutputKeys;
@@ -10,25 +11,62 @@
1011
import javax.xml.transform.sax.SAXSource;
1112
import javax.xml.transform.sax.SAXTransformerFactory;
1213
import javax.xml.transform.stream.StreamResult;
13-
1414
import org.xml.sax.InputSource;
1515

16+
import ws.http.tools.File;
1617
import ws.http.tools.json.JSON;
1718
import ws.http.tools.json.JsonArray;
1819
import ws.http.tools.json.JsonObject;
1920
import ws.http.tools.json.JsonValue;
2021

2122
public class XML {
2223

23-
public static String toXML(Object value, String tag)
24+
public static HashMap<?, ?> parseXML(String xml)
25+
{
26+
return XMLParser.toMap(xml);
27+
}
28+
29+
public static HashMap<?, ?> parseXMLFile(String path, boolean isUrl) {
30+
if (path == null) {
31+
throw new NullPointerException("path is null");
32+
}
33+
if ( isUrl )
34+
{
35+
return parseXML(File.readFromURL(path));
36+
}
37+
38+
return parseXML(File.readFromPath(path));
39+
}
40+
41+
public static String toJSON(String xml)
42+
{
43+
HashMap<?, ?> map = parseXML(xml);
44+
return JSON.toJSON(map);
45+
}
46+
47+
public static String toXML(Object value)
48+
{
49+
return toXML(value, "xml");
50+
}
51+
52+
public static String toXML(Object value, String rootTag)
2453
{
2554
if (value instanceof JsonValue)
2655
{
27-
return prettyXml(jsonToXML((JsonValue) value, tag));
56+
return prettyXml(jsonToXML((JsonValue) value, rootTag));
2857
}
29-
value = JSON.toJSON(value);
30-
value = JSON.parseJSON((String) value);
31-
return prettyXml(jsonToXML((JsonValue) value, tag));
58+
59+
if (value instanceof String)
60+
{
61+
value = JSON.parseJSON((String) value);
62+
}
63+
else
64+
{
65+
value = JSON.toJSON(value);
66+
value = JSON.parseJSON((String) value);
67+
}
68+
69+
return prettyXml(jsonToXML((JsonValue) value, rootTag));
3270
}
3371

3472
private static String jsonToXML(JsonValue json, String tag)
@@ -90,8 +128,6 @@ private static String jsonToXML(JsonValue json, String tag)
90128
sb.append('>');
91129
}
92130
}
93-
94-
95131
}
96132

97133
return sb.toString();
@@ -122,12 +158,13 @@ private static String jsonToXML(JsonValue json, String tag)
122158

123159
return "<" + tag + ">" + val + "</" + tag + ">";
124160
}
125-
161+
126162
private static String prettyXml(String xml){
163+
127164
try{
128165
Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
129166
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
130-
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
167+
serializer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
131168
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
132169
Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
133170
StreamResult res = new StreamResult(new ByteArrayOutputStream());
@@ -138,15 +175,6 @@ private static String prettyXml(String xml){
138175
}
139176
}
140177

141-
public static XmlValue parseXML(String string) {
142-
143-
return null;
144-
}
145-
146178

147-
public static XmlValue query() {
148-
149-
return null;
150-
}
151179

152180
}

src/ws/http/tools/xml/XMLException.java

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,10 @@
11
package ws.http.tools.xml;
22

3-
/**
4-
* The JSONException is thrown by the JSON.org classes when things are amiss.
5-
*
6-
* @author JSON.org
7-
* @version 2015-12-09
8-
*/
3+
@SuppressWarnings("serial")
94
public class XMLException extends RuntimeException {
10-
/** Serialization ID */
11-
private static final long serialVersionUID = 0;
12-
5+
136
/**
14-
* Constructs a JSONException with an explanatory message.
7+
* Constructs a XMLException with an explanatory message.
158
*
169
* @param message
1710
* Detail about the reason for the exception.
@@ -21,7 +14,7 @@ public XMLException(final String message) {
2114
}
2215

2316
/**
24-
* Constructs a JSONException with an explanatory message and cause.
17+
* Constructs a XMLException with an explanatory message and cause.
2518
*
2619
* @param message
2720
* Detail about the reason for the exception.
@@ -33,7 +26,7 @@ public XMLException(final String message, final Throwable cause) {
3326
}
3427

3528
/**
36-
* Constructs a new JSONException with the specified cause.
29+
* Constructs a new XMLException with the specified cause.
3730
*
3831
* @param cause
3932
* The cause.

0 commit comments

Comments
 (0)