package test_json_uri; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.function.BiConsumer; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonStructure; import javax.json.JsonValue; public class TestJsonUri { public static void dump(String tag, String val) { System.out.println(tag + " " + val); } public static void testURI() throws MalformedURLException { BiConsumer<String,String> dump; { String urlString = "http://192.168.21.77:8080/swp/mainPage?aa=11&bb%3D22"; System.out.println(urlString); URI uri = URI.create(urlString); System.out.println("URI path " + uri.getPath()); System.out.println("URI query " + uri.getQuery());//解碼 URL url2 = new URL(urlString); dump("URL", url2.getPath()); dump("URL", url2.getQuery()); //System.out.println("URL query " + url2.getQuery());//不解碼 } { String urlString = "http://192.168.21.77:8080/swp/mainPage?aa=11&bb%3D22"; System.out.println(urlString); URI uri = URI.create(urlString); // System.out.println(uri.getPath()); // System.out.println(uri.getQuery());//解碼 dump("URI", uri.getPath()); dump("URI", uri.getQuery()); URL url2 = new URL(urlString); //System.out.println(url2.getQuery());//不解碼 dump("URL", url2.getPath()); dump("URL", url2.getQuery()); } } public static void navigateTree(JsonValue tree, String key) { if (key != null) System.out.print("Key " + key + ":"); switch(tree.getValueType()) { case OBJECT: System.out.println("OBJECT"); JsonObject obj = (JsonObject) tree; for (String name : obj.keySet()) { navigateTree(obj.get(name), name); } break; case ARRAY: System.out.println("ARRAY"); JsonArray arr = (JsonArray) tree; for (JsonValue val : arr) { navigateTree(val, null); } break; case STRING: JsonString st = (JsonString) tree; System.out.println("STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; System.out.println("NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: System.out.println(tree.getValueType().toString()); break; } } public static void main(String[] args) throws MalformedURLException { String str = "{\"code\":0, \"err\":\"invalid url\"}"; StringReader in = new StringReader(str); JsonReader reader = Json.createReader(in); JsonStructure jsonst = reader.read(); navigateTree(jsonst, null); JsonObject model = Json.createObjectBuilder() .add("firstName", "Duke") .add("lastName", "Java") .add("phoneNumbers", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number","111-333"))).build(); System.out.println(model.toString()); testURI(); } }