Friends, I have a problem in开发者_如何学运维 parsing the json content directly from url given http://samplejson.com/transactions.json, but when i store the same url content as a text file in my res/raw folder it parse the data as well,but when fetching the url content from net it shows an exception (i.e) A JSONArray text must starts with '[' at character 1 of...
what's the wrong here.help me to fix this problem
URL url_net = new URL("http://samplejson.com/transactions.json");
InputStream is = url_net.openStream();
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++) { }
OK, your code seems to be reading all the HTTP including the headers. That is why yours does not start with "[".
Here is the code that I use to get back the string content of an HTTP GET:
public static String getStringContent(String uri) throws Exception {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
}
finally {
// any cleanup code...
}
}
精彩评论