Android从网址解析json

时间:2017-07-16 02:13:28

标签: android json

我可以用这种方式从一个url解析json,我的json看起来像这样;

def OnDown(event):
     toggle = "True"
     return True


def OnUp(event):
    toggle = "False"
    return True

这是我的Android代码,它完美无缺;

[
  {"rank":1,"title":"The Shawshank Redemption"},
  {"rank":2,"title":"The Godfather"},
  {"rank":3,"title":"The Godfather: Part II"},
  {"rank":4,"title":"The Dark Knight"}
]

我想解析这个json,但我无法解析这个json,我不知道。

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private SwipeListAdapter adapter;
    private List<Movie> movieList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        movieList = new ArrayList<>();
        adapter = new SwipeListAdapter(this, movieList);
        listView.setAdapter(adapter);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fetchMovies();
            };
        });
    }

    private void fetchMovies() {
        String url = "http://www.url.com/test.json";
        JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response.length() > 0) {
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject movieObj = response.getJSONObject(i);
                                    int rank = movieObj.getInt("rank");
                                    String title = movieObj.getString("title");
                                    Movie m = new Movie(rank, title);
                                    movieList.add(0, m);
                                } catch (JSONException e) {
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        MyApplication.getInstance().addToRequestQueue(req);
    }
}

我该怎么做?

谢谢。

1 个答案:

答案 0 :(得分:2)

我强烈建议转向Gson。

如果您不想进行更改,以下是fetchMovies的代码:

R