2

是我的 JSON 链接,以及它的外观:

{
"to": "CAD", 
"rate": 1.0223997600000001, 
"from": "USD", 
"v": 5.1119988000000003
}

我试过这个语法:

JSONObject o = new JSONObject(sourceString);
String from = o.getString("from");

但它没有用。

4

3 回答 3

1

你可以创建一个类

public class Abc {
String to;
String rate;
String from;
String v;
}

然后可以使用下面的代码进行解析

JsonObject obj= gson.fromJson(DATA,Abc.class);

其中 DATA 将是您的 gson 字符串。

于 2013-03-19T05:30:56.963 回答
1

你是在模拟器上运行的吗?或者,如果您在设备上运行它,然后在您的互联网连接上关闭它,它会起作用。

于 2013-03-19T05:34:36.340 回答
0

你好检查这个代码它给你的结果是日志(错误)

protected void getJSONFromURL(String string) {
        // TODO Auto-generated method stub
        string = "http://rate-exchange.appspot.com/currency?from=USD&to=CAD&q=5";
        String is = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet Get = new HttpGet(string);

            HttpResponse responce = httpclient.execute(Get);
            HttpEntity entity = responce.getEntity();
            is = EntityUtils.toString(entity, "UTF-8");
            Log.e("responce-->", "" + is.toString());

            if (!is.toString().equalsIgnoreCase("")) {
                JSONObject ob = new JSONObject(is.toString());
                String to = ob.getString("to");
                Log.e("to", "" + to);
                String from = ob.getString("from");
                Log.e("from", "" + from);
                double rate = ob.getDouble("rate");
                Log.e("rate", "" + rate);
                double v = ob.getDouble("v");
                Log.e("v", "" + v);
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("call http :", e.getMessage().toString());
            is = null;
        }

    }

如果您在 3.0 以上操作系统,则还包括此代码;

int SDK_INT = android.os.Build.VERSION.SDK_INT;

if (SDK_INT>8){

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

}

你的结果在这里:

03-19 11:23:22.745: E/responce-->(811): {"to": "CAD", "rate": 1.0220998400000001, "from": "USD", "v": 5.1104992000000005}
03-19 11:23:22.745: E/to(811): CAD
03-19 11:23:22.776: E/from(811): USD
03-19 11:23:22.776: E/rate(811): 1.02209984
03-19 11:23:22.791: E/v(811): 5.1104992000000005
于 2013-03-19T05:54:57.183 回答