如何在Android上从HTTP获取JSON到Java对象

时间:2015-08-01 06:05:27

标签: java android json http

我想从HTTP获取JSON并将其解析为我的Android应用中的对象。 我已经尝试过使用AsyncTask的Spring Framework,但是每个人都说它被弃用了。

那么我怎样才能实现这一目标,或者有人为我提供教程链接?

4 个答案:

答案 0 :(得分:2)

我会在本文中扩展Denis提案以及何时使用给定的库。

首先来自几个月前的文章JSON Libraries Performance Comparison

如果你不想读:

  • 将Jackson库用于 JSON数据
  • 将GSON用于小型 JSON数据(大多数请求都相当小)

答案 1 :(得分:1)

参考这个,它会给你在String中的响应,你可以在jsonObject中转换它

public static String postUrlResponse(String url,List<NameValuePair> urlParameters) 
{
    try
    {
        System.out.println("URL : " + url);
        HttpParams httpParams = new BasicHttpParams();
        HttpClient client = new DefaultHttpClient(httpParams);
        HttpPost post = new HttpPost(url);

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + 
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }
    catch(Exception e)
    {
        e.printStackTrace();
        return e.toString();
    }
}

答案 2 :(得分:1)

解析JSON的最佳库是Jackson
Here是非常有用的教程。根据{{​​3}}文章,你可以看到杰克逊是最快的

答案 3 :(得分:0)

回答我自己的问题,谢谢大家。

public static List<Events> getEvents() {

    List<Events> ret = new ArrayList<Events>();
    ProgressDialog pr = new ProgressDialog(context);

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


    // YOUR URL GOES HERE
    String getUrl = "http://example.nl/CALL.ashx?Onderdeel=Feeds&AuthToken=" + WWIBCore.AuthToken;
    HttpClient http = new DefaultHttpClient();

    HttpResponse response = null;
    HttpGet getMethod = new HttpGet(getUrl);
    try {
        response = http.execute(getMethod);

        // CONVERT RESPONSE TO STRING
        String result = EntityUtils.toString(response.getEntity());

        // CONVERT RESPONSE STRING TO JSON ARRAY
        JSONArray ja = new JSONArray(result);

        // ITERATE THROUGH AND RETRIEVE EVENTS FIELDS
        int n = ja.length();

        for (int i = 0; i < n; i++) {

            // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
            JSONObject jo = ja.getJSONObject(i);

            // CONVERT DATA FIELDS TO EVENTS OBJECT
            Events e = new Events();
            e.setNaam(jo.getString(("Naam")));
            e.setContent(jo.getString("Content"));

            ret.add(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    pr.dismiss();
    return ret;
}