如何从URL访问应用程序中的JSON数据?

时间:2018-09-27 06:59:20

标签: java android json

JSon Data

在此URL中,我有一些Json数据。如何使用该URL将数据获取到我的Andorid应用程序。

我在Google中看到过引用。但是没有解决办法。

我是Andorid的新手。

请帮助我。

4 个答案:

答案 0 :(得分:1)

执行此操作:

步骤-1 在您的gradle中导入排球库:

实现'com.android.volley:volley:1.1.0'

然后用Java编写此代码:

    ProgressDialog progressDialog; // define globally

 public void getLocations(){   //call this method onCreate or on OnClickEvent

    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Feteching....");
    progressDialog.setCancelable(false);
    progressDialog.show();

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

    StringRequest request = new StringRequest(Request.Method.GET, "YOUR URL", new Response.Listener<String>() { //you can change here POST/GET
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            System.out.println("Response : " + response);
            try {

                 JSONObject jsonResponse = new JSONObject(response);

                  JSONArray locations = jsonResponse.getJSONArray("LOCATIONS");
                  for (int i = 0; i < locations.length(); i++) {
                  JSONObject jsonObject = locations.getJSONObject(i);

               String name = jSONObject.getString("name");
                String lat = jSONObject.getString("lat");
                String lng = jSONObject.getString("lng");
                 System.out.println("LOCATIONS : " + name +"," + lat + "," + lng);

               // check this print in logcats

                 }
               } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("VolloError " + error);
            progressDialog.dismiss();
            Toast.makeText(YourActivity.this, "Network Connection Error...!!!", Toast.LENGTH_SHORT).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            // use params when you are using POST method

            return params;
        }

    };

    request.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 50000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 50000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });
    queue.add(request);
}

答案 1 :(得分:0)

您可以使用Retrofit库来解析JSON数据,Retrofit具有比volley更好的性能。

1)将这些依赖项添加到您的应用gradle文件中。

public interface RetrofitInterface {
@GET("lots.json")
Call<List<Your_pojo_class>> getlocation();
}

2)创建RetrofitInterface来定义诸如@get或@post之类的注释。

public class location {
private String Name;
private String Lat;
private String Lng;

public String getName() {
    return Name;
}

public void getLat() {
    return Lat;
}
public void getLng() {
    return Lng;
}
}

3)创建您的pojo类

import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Controller implements Callback<List<Change>> {

static final String BASE_URL = "wsp:88/parking/";

public void start() {
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RetrofitInterface retro = retrofit.create(RetrofitInterface.class);

    Call<List<location>> call =retro.getlocation();
    call.enqueue(this);

}

@Override
public void onResponse(Call<List<location>> call, Response<List<location>> response) {
    // add your on response activity here
}

@Override
public void onFailure(Call<List<location>> call, Throwable t) {
    // add your on failure activity here

}
}

4)现在回到mainActivity,您将在其中编写Api服务及其响应和失败事件。

{{1}}

点击此链接可获取更多信息或更好地理解。enter link description here

答案 2 :(得分:-1)

尝试一下

    String name,lat,lng;

RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, YOUR_API_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            JSONObject jsonObject = new JSONObject(response);
            JSONArray jSONArray = jsonObject.getJSONArray("LOCATIONS");
            for (int i = 0; i < clients.length(); i++) {

                    JSONObject jSONObject1 = jSONArray.getJSONObject(i);
                    name = jSONObject1.getString("name");
                    lat = jSONObject1.getString("lat");
                    lng = jSONObject1.getString("lng");


            }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {

                } catch (UnsupportedEncodingException uee) {

                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/json");

                return params;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {
                    responseString = String.valueOf(response.statusCode);
                    // can get more details such as response.headers
                    try {

                    } catch (Exception e) {

                    }
                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        stringRequest.setRetryPolicy(new RetryPolicy() {
            @Override
            public int getCurrentTimeout() {
                return 50000;
            }

            @Override
            public int getCurrentRetryCount() {
                return 50000;
            }

            @Override
            public void retry(VolleyError error) throws VolleyError {

            }
        });
        requestQueue.add(stringRequest);

    }

让我知道这是否可行。

答案 3 :(得分:-1)

您应该使用Retrofit

之类的库