从URL读取json数据时出错。下面是我想要的代码。请纠正我在哪里出错。
public class ReadingJsonData {
public static void main(String[] args) throws JSONException {
JSONObject json = readJsonFromUrl("http://requestb.in/pp1mzapp");
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText.trim());
return json;
} finally {
is.close();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
我的URL中的Json对象看起来像
{"FormID":"2095180","UniqueID":"213482652","Name":{"first":"Something","last":"New"},"Date of Birth":"Feb 03, 1926","Last 4 Digits of SSN":"1234","Week Beginning Date":"Jan 01, 2012","Week Ending Date":"Feb 03, 2014","Email":"something.new@something.gov":""}
答案 0 :(得分:1)
您的Json不正确,请参阅最后一行
{
"FormID": "2095180",
"UniqueID": "213482652",
"Name": {
"first": "Something",
"last": "New"
},
"Date of Birth": "Feb 03, 1926",
"Last 4 Digits of SSN": "1234",
"Week Beginning Date": "Jan 01, 2012",
"Week Ending Date": "Feb 03, 2014",
"Email": "something.new@something.gov": ""
}