2015-08-16 35 views
1

現在我試圖讓JSON數組離子(https://github.com/koush/ion) 但我得到的錯誤:未處理的異常:org.json.JSONException :(Android的未處理的異常:org.json.JSONException離子

我的JSON:

[{"title":"Hello world","text":"This is the text"}] 

我的代碼:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_json); 

     Ion.with(MyActivity.this) 
       .load(getString(R.string.json_url)) 
       .asJsonArray() 
       .setCallback(new FutureCallback<JSONArray>() { 
        @Override 
        public void onCompleted(Exception e, JSONArray result) { 
         if (e != null) { 
          Toast.makeText(MyJson.this, "Error loading strings", Toast.LENGTH_LONG).show(); 
          return; 
         } 
         JSONObject c = result.getJSONObject(0); 
         if (c.has("title")) title = c.getString("title"); 
         if (c.has("text")) text = c.getString("text"); 


        } 
       }); 

    } 

有人能告訴我我做錯了嗎? :(

編輯:

Error:(48, 17) error: method setCallback in interface Future<T> cannot be applied to given types; 
required: FutureCallback<JsonArray> 
found: <anonymous FutureCallback<JSONArray>> 
reason: actual argument <anonymous FutureCallback<JSONArray>> cannot be converted to FutureCallback<JsonArray> by method invocation conversion 
where T is a type-variable: 
T extends Object declared in interface Future 
+0

完整的堆棧跟蹤將會很有幫助:在什麼情況下會發生這種異常?無論如何,也可能想要添加'try/catch'塊來處理它。 – solar

+0

'JSONObject c = result.getJSONObject(0);','title = c.getString(「title」);','text = c.getString(「text」);'我正在使用Android Studio。 (出現紅色下劃線) – user5195185

+0

那麼,你確定'result'數組是一致的而不是空的嗎?在我看來,當你嘗試執行'getJSONObject(0)'時會出現問題。 看看[這裏](http://stackoverflow.com/questions/30289189/androidunhandled-exception-org-json-jsonexception)來處理你的異常,就像我之前推薦的那樣。 – solar

回答

1

我解決了這個問題的傢伙:)!

我改變:JSONArray(org.json.JSONArray)到:JsonArray(com.google.gson.JsonArray)

我添加了這個:

JsonObject c = result.get(0).getAsJsonObject(); 

這是現在的代碼:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_json); 

     Ion.with(MyActivity.this) 
       .load(getString(R.string.json_url)) 
       .asJsonArray() 
       .setCallback(new FutureCallback<JsonArray>() { 
        @Override 
        public void onCompleted(Exception e, JsonArray result) { 
         if (e != null) { 
          Toast.makeText(MyJson.this, "Error loading strings", Toast.LENGTH_LONG).show(); 
          return; 
         } 
         JsonObject c = result.get(0).getAsJsonObject(); 
         if (c.has("title")) title = c.get("title").getAsString(); 
         if (c.has("text")) text = c.get("text").getAsString(); 


        } 
       }); 

    } 

這解決了問題!