//这里我放了我的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");
答案 0 :(得分:1)
问题在于您的JSON
:
{
"to": "USD",
"rate": 0.98087299999999999,
"from": "CAD",
"v": 1.961746
}
不是JSONArray
而是JSONObject
不包含数组但只包含键值对。因此,您只需将其指定为Object并从中获取数据:
JSONObject o = new JSONObject(sourceString);
String from = o.getString("from"); // getting value CAD with key from