2013-03-19 38 views
2

Here是我的JSON解析鏈接直接JSON對象,它的外觀:如何只從JSON

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

我想這句法:

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

,但沒有奏效。

+3

*但不工作的*手段?你能解釋更多什麼問題你在解析當前json – 2013-03-19 04:55:38

+0

你得到什麼錯誤?由於JSON看起來很好,並且您的代碼片段用於解析它,所以也是正確的。 – SudoRahul 2013-03-19 05:00:20

+0

您的回覆和解析都正確的問題在哪裏 – 2013-03-19 05:24:43

回答

1

您可以創建一個類

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

,然後可以使用下面的代碼解析

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

,其中數據將是你GSON字符串。

+0

您的問題是否解決? – 2013-03-19 08:19:23

1

你在模擬器上運行它嗎? 或者,如果你在設備上破壞它,然後關閉並在你的互聯網連接,它會工作。

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; 
     } 

    } 

如果你yseing 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