【问题标题】:Android Volley JSON parseAndroid Volley JSON 解析
【发布时间】:2016-08-04 01:54:02
【问题描述】:

我正在尝试从服务器获取数据并将其显示在 ListView 中,但它在这里不起作用,我正在使用 Volley 库。我正在找Volley的代码,但是我找不到,请问我可以得到这个对应的代码吗?

JSONParse.java:

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.IOException;  
import java.io.InputStream;   
import java.io.InputStreamReader;
import org.apache.http.client.HttpClient;
import org.json.JSONException;

public class JSONParse {
    static InputStream iStream=null;
    static JSONArray jarray=null;
    static String json="";

    public JSONParse(){
    }

    public JSONArray getJSONFromUrl(String url){
        StringBuilder builder=new StringBuilder();
        HttpClient client=new DefaultHttpClient();

        //------------J.G-----------------
        /*HttpClient client=new DefaultHttpClient();
        HttpGet httpGet=new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("jwttoken", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJFUk0iLCJpc3MiOiJFUk0iLCJpYXQiOjE0MzM2OTczMjd9.2zd4OlKjW3Yfcd_q2FOoyEGpNrFbf7EuHeIkZ8ponr0");*/
        try {
            HttpGet httpGet=new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json");
            httpGet.setHeader("jwttoken",        "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJFUk0iLCJpc3MiOiJFUk0iLCJpYXQiOjE0MzM2OTczMjd9.2      zd4OlKjW3Yfcd_q2FOoyEGpNrFbf7EuHeIkZ8ponr0");

            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new   InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jarray= new JSONArray(builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data"+ e.toString());
        }
        return jarray;
    }
}

【问题讨论】:

  • 不,你不会得到代码,你需要自己尝试。

标签: java android json android-volley


【解决方案1】:

像这样实现你的代码:

 public void getData(){

    //Showing a progress dialog
    final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    loading.dismiss();
                    parseData(response);

                }
            },
                    new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub

                    Log.d("Json Error:",error.toString());

                }
            });


    //Creating request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(jsonObjectRequest);
}

public void parseData(JSONObject object){

    try {

        JSONArray jsonArray=object.getJSONArray("worldpopulation");
        Log.d("Json Array:", jsonArray.toString());

        for (int i=0;i<jsonArray.length();i++){
            Data data=new Data();
            JSONObject obj;
            try {
                obj=jsonArray.getJSONObject(i);

                data.setImageUrl(obj.getString("flag"));
                data.setName(obj.getString("country"));
                data.setRank(obj.getString("rank"));
                data.setPopulation(obj.getString("population"));

                items.add(data);

            }
            catch (JSONException e){
                Log.d("Error in Parse Object:", e.toString());
            }
        }
    } catch (JSONException e) {
        Log.d("Error in parse Array:", e.toString());
    }
    mAdapter = new MyAdapter(items,this);
    mRecyclerView.setAdapter(mAdapter);
}

更多信息请关注Tutorial

【讨论】:

    【解决方案2】:

    不确定这是不是你想要的: JsonRequest.java

    下面是我使用 Volley 解析 Json 数据的方法。

    说一个url代表下面的Json数据:

    [ { "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } }, { "name" : "Tommy", "email" : "tommy@gmail.com", "phone" : { "home" : "08946 000000", "mobile" : "0000000000" } } ]

    解析代码如下:

    JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
    
                    try {
                        // Parsing json array response
                        // loop through each json object
                        jsonResponse = "";
                        for (int i = 0; i < response.length(); i++) {
    
                            JSONObject person = (JSONObject) response
                                    .get(i);
    
                            String name = person.getString("name");
                            String email = person.getString("email");
                            JSONObject phone = person
                                    .getJSONObject("phone");
                            String home = phone.getString("home");
                            String mobile = phone.getString("mobile");
    
                            jsonResponse += "Name: " + name + "\n\n";
                            jsonResponse += "Email: " + email + "\n\n";
                            jsonResponse += "Home: " + home + "\n\n";
                            jsonResponse += "Mobile: " + mobile + "\n\n\n";
    
                        }
    
                        txtResponse.setText(jsonResponse);
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),
                                "Error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
    
                    hidepDialog();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_SHORT).show();
                    hidepDialog();
                }
            });
    
    // Adding request to request queue, please substitute here with your own queue
    VolleyQueue.add(req);
    

    更多参考请看link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多