无法从JSON Array解析两个不同的对象

时间:2017-07-27 10:31:48

标签: android json

我试图从JSON数组中获取两个不同的对象,但不知怎的,我无法获取第二个对象(" opening_hours")。不确定我是否正确解析它。我也想得到元素" open_now"来自" opening_hours"并将其设置为方法" SetAuthor"。下面是JSON数组的代码URL:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=%22%20+%20cafe+%20%22&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CODE_SPEECH_INPUT = 100;
    private TextView mVoiceInputTv;
    private ImageButton mSpeakBtn;

    private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
    private GoogleApiClient googleApiClient;

    int status;

    ArrayList<String> result;

    ArrayList<Elements> elementList;
    ArrayList<Elements> elementListtwo;
    ElementAdaptor adapter;

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

        //mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
        mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
        mSpeakBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startVoiceInput();
            }
        });

    }

    private void startVoiceInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Welcome to Harman Framework");
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {
                    result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    //mVoiceInputTv.setText(result.get(0));
                    Toast.makeText(getApplicationContext(), "You searched : " + result.get(0), Toast.LENGTH_LONG).show();

                    elementList = new ArrayList<Elements>();

                    new JSONAsyncTask().execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk");

                    ListView listview = (ListView)findViewById(R.id.list);
                    adapter = new ElementAdaptor(getApplicationContext(), R.layout.row, elementList);

                    listview.setAdapter(adapter);

                    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                                long id) {
                            Intent intent = new Intent(getApplicationContext(), DescriptionActivity.class);
                            intent.putExtra("title", elementList.get(position).getTitle());
                            intent.putExtra("author", elementList.get(position).getAuthor());
                            intent.putExtra("publishedat", elementList.get(position).getPublishedat());
                            intent.putExtra("description", elementList.get(position).getDescription());
                            intent.putExtra("imageurl", elementList.get(position).getImage());
                            startActivity(intent);
                        }
                    });

                }
                break;
            }

        }
    }

    //String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk";

    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading.......");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                HttpGet httppost = new HttpGet(urls[0]);

                HttpParams httpParameters = new BasicHttpParams();

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);
                HttpParams params = httpclient.getParams();

                status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("results");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Elements parameters = new Elements();

                        parameters.setTitle(object.getString("name"));
                        parameters.setImage(object.getString("icon"));

                        elementList.add(parameters);
                    }

                    JSONArray jarraytwo = jsono.getJSONArray("opening_hours");

                    for (int i = 0; i < jarraytwo.length(); i++) {
                        JSONObject objecttwo = jarraytwo.getJSONObject(i);

                        Elements parameterstwo = new Elements();

                        parameterstwo.setAuthor(objecttwo.getString("open_now"));

                        Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();

                        elementListtwo.add(parameterstwo);
                    }

                    return true;
                }

            }  catch (JSONException e3) {
                e3.printStackTrace();
            }  catch (IOException e2) {
                e2.printStackTrace();
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
            adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
    }



}

完整活动代码:

public class Elements {

    private String title;
    private String description;
    private String author;
    private String publishedat;
    private String urltoimage;

    public Elements() {
        // TODO Auto-generated constructor stub
    }

    public Elements(String title, String description, String author,
                    String publishedat, String urltoimage) {

        this.title = title;
        this.description = description;
        this.author = author;
        this.publishedat = publishedat;
        this.urltoimage = urltoimage;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublishedat() {
        return publishedat;
    }

    public void setPublishedat(String publishedat) {
        this.publishedat = publishedat;
    }

    public String getImage() {
        return urltoimage;
    }

    public void setImage(String urltoimage) {
        this.urltoimage = urltoimage;
    }

}

Elements.java

{{1}}

2 个答案:

答案 0 :(得分:1)

首先&#34; opening_hours&#34;是JSONObject而不是JSONArray。

第二件事&#34; opening_hours&#34;对象内部&#34;结果&#34;阵列。

所以解析应该是这样的

for (int i = 0; i < jarray.length(); i++) {
     JSONObject object = jarray.getJSONObject(i);

     Elements parameters = new Elements();

     parameters.setTitle(object.getString("name"));
     parameters.setImage(object.getString("icon"));

     elementList.add(parameters);

     // add here
     JSONObject jarraytwo = jsono.getJSONObject("opening_hours");
}

答案 1 :(得分:0)

尝试此JSON解析

                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("results");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Elements parameters = new Elements();

                    parameters.setTitle(object.getString("name"));
                    parameters.setImage(object.getString("icon"));

                    elementList.add(parameters);


                JSONArray jarraytwo = object.getJSONArray("opening_hours");

                for (int i = 0; i < jarraytwo.length(); i++) {
                    JSONObject objecttwo = jarraytwo.getJSONObject(i);

                    Elements parameterstwo = new Elements();

                    parameterstwo.setAuthor(objecttwo.getString("open_now"));

                    Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();

                    elementListtwo.add(parameterstwo);
                }
                }