我正在使用 GSON 解析 JSON 数据。这是我的代码 -
public class TestProg {
private static final String storeURL = "https://abcd"; //Haven't given the URL here completely
public static void main(String[] args) throws Exception {
String getData = getDataFromURL(storeURL);
Gson gson = new Gson();
Test rs = (Test) gson.fromJson(getData.toString(), Test.class);
List<TestB> testData = rs.getContent();
for(TestB retStr:testData)
{
System.out.println(retStr.getTitle());
System.out.println(retStr.getOwner());
}
}
public static String getDataFromURL(String url) throws Exception {
String dataFromURL = readUrl(url);
return dataFromURL;
}
public static String readUrl(String inputURL) throws IOException {
URL url = null;
BufferedReader br = null;
StringBuilder sb = null;
HttpURLConnection conn = null;
try {
url = new URL(inputURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
System.out.println("Failed : HTTP error code :" + conn.getResponseCode());
}
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (MalformedURLException e) {
System.out.print("Exception occured while reading data from the URL "+ e.getMessage());
return null;
} finally {
if (br != null)
br.close();
conn.disconnect();
}
}
}
运行代码时出现以下错误 -
Exception in thread "main" com.google.gson.JsonSyntaxException: java.net.MalformedURLException: no protocol: www.abc.com
at com.google.gson.Gson.fromJson(Gson.java:818)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
我不能在这里包含测试类,因为它有一些敏感数据。