Android Unhandled异常:带有ion的org.json.JSONException

时间:2015-08-16 18:14:49

标签: java android json

我现在正试图用离子(https://github.com/koush/ion)获取json数组 但我收到错误:未处理的异常: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

1 个答案:

答案 0 :(得分: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();


                    }
                });

    }

这解决了这个问题!