//在这里我放了我的json文件,它只返回数组内部元素而不是数组名所以我试图解析//它但是没有数组名我做不到
//我的json
{
"to": "USD",
"rate": 0.98087299999999999,
"from": "CAD",
"v": 1.961746
}
//从url获取getJson的代码
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 从服务器读取数据
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
// 解析
url = "http://rate-exchange.appspot.com/currency?from=CAD&to=INR&q=5";
JSONParser jParser = new JSONParser();
json = jParser.getJSONFromUrl(url);
data_to = json.getString("to");
data_rate = json.getDouble("rate");
data_from = json.getString("from");
data_value =json.getDouble("v");