我试图解析以下链接中的数据

时间:2016-11-16 10:56:35

标签: android json android-asynctask android-volley getjson

" http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - 我试图解析的链接

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final Button GetServerData = (Button) findViewById(R.id.GetServerData);
        GetServerData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // WebServer Request URL
                String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";

                // Use AsyncTask execute Method To Prevent ANR Problem
                new LongOperation().execute(serverURL);
            }
        });
    }
        private class LongOperation extends AsyncTask<String, Void, Void> {
            private final HttpClient Client = new DefaultHttpClient();
            private String Content;
            private String Error = null;
            private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
            String data = "";
            TextView uiUpdate = (TextView) findViewById(R.id.textView2);
            TextView jsonParsed = (TextView) findViewById(R.id.textView3);
            int sizeData = 0;
            EditText serverText = (EditText) findViewById(R.id.textView);

            protected void onPreExecute() {
                // NOTE: You can call UI Element here.

                //Start Progress Dialog (Message)

                Dialog.setMessage("Please wait..");
                Dialog.show();

                try {
                    // Set Request parameter
                    data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            protected Void doInBackground(String... urls) {
                /************ Make Post Call To Web Server ***********/
                BufferedReader reader = null;
                // Send data
                try {
                    // Defined URL  where to send data
                    URL url = new URL(urls[0]);
                    // Send POST data request
                    URLConnection conn = url.openConnection();
                    conn.setDoOutput(true);
                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(data);
                    wr.flush();

                    // Get the server response
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    // Read Server Response
                    while ((line = reader.readLine()) != null) {
                        // Append server response in string
                        sb.append(line + "");
                    }
                    // Append Server Response To Content String
                    Content = sb.toString();
                } catch (Exception e) {
                    Error = e.getMessage();
                } finally {
                    try {

                        reader.close();
                    } catch (Exception ex) {
                    }
                }
                return null;
            }


            protected void onPostExecute(Void unused) {
                // NOTE: You can call UI Element here.

                // Close progress dialog
                Dialog.dismiss();
                if (Error != null) {

                    uiUpdate.setText("Output : " + Error);

                }else
                {
                    //Show Response Json Onscreen(Activity)
                    uiUpdate.setText( Content );

                    /****************** Start Parse Response JSON Data *************/

                    String OutputData = "";
                    try {
                        JSONObject jsono = new JSONObject(Content);
                        JSONObject mainObject = jsono.getJSONObject("data");
                        JSONArray jsonArray = mainObject.getJSONArray("standing");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            // get details2 JSONObject
                            String position = object.optString("position").toString();
                            String team = object.optString("team").toString();

                            OutputData += "Position: " + position + " "
                                    + "Team Name      : " + team + " ";
                        }
                        /****************** End Parse Response JSON Data *************/
                        //Show Parsed Output on screen (activity)
                        jsonParsed.setText( OutputData );
                    }catch (JSONException e) {

                        e.printStackTrace();
                    }

                }
            }

        }

}

**我正在创建一个超级联赛应用程序,显示一流俱乐部粉丝所需的所有数据。正如我刚才所说,我对json解析和从apis获取数据感到困惑。所以任何人都可以向我解释如何更改我的代码或某些链接,这将有助于我纠正它。

上面给出的是我的主要活动的java代码。**

2 个答案:

答案 0 :(得分:0)

谢谢大家的帮助。但我通过互联网搜索找到了答案。在这里,我使用VOLLEY来调用链接。

JSON PARSER CLASS

 public class ParseJSON  {

        public static String[] position1;
        public static String[] team;
        public static String[] points;

        public static final String JSON_ARRAY = "data";

        public static final String CHILD_ARRAY = "standings";

        public static final String KEY_ID = "position";
        public static final String KEY_NAME = "team";

        private JSONObject users = null;
        private JSONArray user2=null;
        private JSONObject user3=null;

        private String json;

        public ParseJSON(String json){
            this.json = json;
        }
        protected void parseJSON() {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(json);
                users = jsonObject.getJSONObject(JSON_ARRAY);
                try {
                    user2=users.getJSONArray(CHILD_ARRAY);
                    position1 = new String[user2.length()];
                    team = new String[user2.length()];
                    points=new String[user2.length()];
                    for (int i = 0; i < user2.length(); i++) {

                        JSONObject jo = user2.getJSONObject(i);
                       try {
                           user3=jo.getJSONObject("overall");
                           points[i] = user3.getString("points");
                           System.out.println("Message me: "+points[i]);
                       }catch (Exception e)
                       {
                           e.printStackTrace();
                       }
                        position1[i] = jo.getString(KEY_ID);
                        team[i] = jo.getString(KEY_NAME);
                        System.out.println("Message me: "+position1[i]);
                        System.out.println("Message me: "+team[i]);


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

主要活动类

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {


        public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
        private Button buttonGet;
        private ListView listView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            buttonGet = (Button) findViewById(R.id.buttonGet);
            buttonGet.setOnClickListener(this);
            listView = (ListView) findViewById(R.id.listView);
        }

        @Override
        public void onClick(View v) {
            sendRequest();
        }
        private void sendRequest() {
            final StringRequest stringRequest = new StringRequest(JSON_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            showJSON(response);

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        }
        private void showJSON(String json){
            ParseJSON pj = new ParseJSON(json);
            pj.parseJSON();
            CustomList cl = new CustomList(this,    ParseJSON.position1,ParseJSON.team,ParseJSON.points);
            listView.setAdapter(cl);
        }    
    }

将数据添加到列表视图的自定义类

public class CustomList  extends ArrayAdapter<String> {

    private String[] position1;
    private String[] team;
    private String[] points;
    private Activity context;

    public CustomList(Activity context, String[] position1, String[] team, String[] points) {
        super(context, R.layout.list_view_layout, position1);
        this.context = context;
        this.position1 = position1;
        this.team = team;
        this.points = points;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
        TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
        TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
        TextView points1 = (TextView) listViewItem.findViewById(R.id.points);


        pos1.setText("Position: "+position1[position]);
        teamname.setText("Team: "+team[position]);
        points1.setText("Points: "+points[position]);


        return listViewItem;
    }
}

答案 1 :(得分:-1)

步骤1:使用Retroft + RxJava进行异步API调用

第2步:使用Gson进行序列化和反序列化。

步骤3:使用json到POJO以获得模型类

简化代码。