我遇到以下错误:
Exception in thread "main" java.lang.RuntimeException: java.net.MalformedURLException: no protocol: url
at test.getJsonFromUrl(test.java:67)
at test.main(test.java:75)
Caused by: java.net.MalformedURLException: no protocol: url
...
这是我的完整代码:
import java.io.Reader;
import java.net.URL;
import com.google.gson.*;
import java.io.IOException;
import java.io.InputStreamReader;
public class test {
public static String getJsonFromUrl(String url){
Gson gson = new GsonBuilder().create();
try{
Reader reader = new InputStreamReader(new URL("url").openStream());
gson.fromJson(reader, String.class);
}catch(IOException e){
throw new RuntimeException(e);
}
return gson.toString();
}
public static void main(String[] args) {
String json = getJsonFromUrl("https://api.kraken.com/0/public/Assets?asset=XBT");
System.out.println(json);
}
}
不知道问题出在哪里,因为如果我在浏览器中复制网址,则会显示JSON内容... 我猜它是一个网址?我怎么能解决它?
答案 0 :(得分:1)
您正在使用字符串文字,而不是变量...
new URL("url").openStream()
应该是
new URL(url).openStream()
注意引号,表示某些内容应解释为字符串
答案 1 :(得分:0)
以下行不正确
gson.fromJson(reader, String.class);
第一个参数是stringify json而不是reader对象。
第二个参数是模型类,而不是String类。
答案 2 :(得分:0)
好的,我改变了两个并且我得到了以下输出:
function listUpcomingEvents() {
var request = gapi.client.calendar.events.list({
'calendarId': 'MyID',
'timeMin': (new Date()).toISOString(), //If i change format here code doesn't work
'showDeleted': false,
'singleEvents': true,
'maxResults': 1,
'orderBy': 'startTime'
});
request.execute(function(resp) {
var events = resp.items;
appendPre('');
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
var when2 = event.end.dateTime;
if (!when2) {
when2 = event.end.date;
}
appendPre(' Fra ' + when + ' Til ' + when2 + ' ' + event.summary)
}
} else {
appendPre('No upcoming events found.');
}
});
}
等等(它不是完整的输出)。这是我的代码:
{serializeNulls:falsefactories:[Factory[typeHierarchy=com.google.gson.JsonElement,adapter=com.google.gson.internal.bind.TypeAdapters$29@52a86356], com.google.gson.internal.bind.ObjectTypeAdapter$1@5ce81285, com.google.gson.internal.Excluder@78c03f1f, Factory[type=java.lang.String,adapter=com.google.gson.internal.bind.TypeAdapters$16@5ec0a365], Factory[type=java.lang.Integer+int,adapter=com.google.gson.internal.bind.TypeAdapters$7@4fe3c938], Factory[type=java.lang.Boolean+boolean,adapter=com.google.gson.internal.bind.TypeAdapters$3@5383967b], Factory[type=java.lang.Byte+byte,adapter=com.google.gson.internal.bind.TypeAdapters$5@2ac273d3], Factory[type=java.lang.Short+short,adapter=com.google.gson.internal.bind.TypeAdapters$6@71423665], Factory[type=java.lang.Long+long,adapter=com.google.gson.internal.bind.TypeAdapters$11@20398b7c], Factory[type=java.lang.Double+double,adapter=com.google.gson.Gson$2@6fc6f14e], Factory[type=java.lang.Float+float,adapte