如果不使用其他JAR或API,严格使用javax.json.*
,如何从网址读取JSON对象?
javadocs表示可能:
JsonReader jsonReader = Json.createReader(new StringReader("[]"));
JsonArray array = jsonReader.readArray();
jsonReader.close();
但并不具体说明如何使用URL or URI。
当前代码:
package net.bounceme.noagenda;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import javax.json.JsonObject;
import static java.lang.System.out;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonReader;
public class NoAgenda {
public static void main(String[] args) {
new NoAgenda().fromURL();
}
private void fromURL() {
try {
String jsonString = callURL("http://www.javascriptkit.com/dhtmltutors/javascriptkit.json");
} catch (IOException ex) {
Logger.getLogger(NoAgenda.class.getName()).log(Level.SEVERE, null, ex);
}
try (JsonReader jsonReader = Json.createReader(new StringReader("[]"))) {
JsonArray array = jsonReader.readArray();
out.println(array.toString());
}
}
public String callURL(String myURL) throws IOException {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
return sb.toString();
}
public JsonObject buildBook() {
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
return value;
}
}
尝试获取此页面的JSON对象:
http://www.javascriptkit.com/dhtmltutors/javascriptkit.json
再次,重新迭代,强调,只使用javax
包。
答案 0 :(得分:1)
你可以做这样的事情,虽然我还没有在javax上使用Json api。
try(InputStream is = new URL(your_url).openStream();
JsonReader reader = Json. createReader(new InputStreamReader(is, "UTF-8"));){
//TODO: Let's start doing Yoga with Json
}
catch(IOException e){
e.printStackTrace();
}