如何从JSON数组中提取单个随机JSONObject

时间:2018-09-11 03:11:09

标签: android json

这是我的JSON数组,带有不同的引号以及其作者姓名。

 {
  "quotes": [
    {
      "id": "4",
      "quote": "whatsapp is bad",
      "author": "William W. Purkey "
    },
    {
      "id": "3",
      "quote": "yahoo is a company",
      "author": "William W. Purkey "
    },
    {
      "id": "1",
      "quote": "Google is a search engine",
      "author": "William W. Purkey "
    }
  ]
}

我想在android中获取单个随机JSON对象。而不是全部。

示例:

 {
  "id": "4",
  "quote": "whatsapp is bad",
  "author": "William W. Purkey "
}

这是我现在在我的Android应用程序中得到的: Getting All JSON Object from Array

这是我的MainActivity.java

    public class MainActivity extends AppCompatActivity {
    private TextView quoteTV, authorTV, startReading;
   // private RequestQueue mQueue;
    private ProgressDialog progress;
    public RequestQueue mQueue;


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

        startReading = findViewById(R.id.startReading);
        quoteTV = findViewById(R.id.quoteTV);
        quoteTV.setVerticalScrollBarEnabled(true);
        quoteTV.setMovementMethod(ScrollingMovementMethod.getInstance());
        quoteTV.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
        authorTV = findViewById(R.id.authorTV);
        final Button buttonParse = findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);

        CardView editProfileLayout = (CardView) findViewById(R.id.authorTVBG);
        editProfileLayout.setVisibility(View.GONE);

        buttonParse.setText("Start Reading");

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                buttonParse.setText("Next Quote");
                CardView editProfileLayout = (CardView) findViewById(R.id.authorTVBG);
                editProfileLayout.setVisibility(View.VISIBLE);
                quoteTV.setText("");
                authorTV.setText("");


                progress = new ProgressDialog(MainActivity.this);
                progress.setMessage("Loading.. Please Wait");
                progress.setCancelable(true);
                progress.show();

                jsonParse();
                startReading.setText("");
            }
        });
    }

    private void jsonParse() {

        String url = "http://myjson.com/q3wr4";

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

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("quotes");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject quotes = jsonArray.getJSONObject(i);

                                int id = quotes.getInt("id");
                                String quote = quotes.getString("quote");
                                String author = quotes.getString("author");

                                progress.hide();

                                quoteTV.append("“ " + String.valueOf(quote) + " ”");
                                authorTV.append("Author " + ": " + String.valueOf(author));

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);

    }
}

我只需要在我的Android应用程序中显示一个报价,而不是显示JSON数组中的所有报价。需要帮忙。在此先感谢

3 个答案:

答案 0 :(得分:1)

密钥是随机分配的jsonArray索引,可以这样完成:

import java.util.Random;
Random r = new Random();
int index = r.nextInt(jsonArray.length()) ; //range is 0~jsonArray.length()

JSONObject quotes = jsonArray.getJSONObject(index);

int id = quotes.getInt("id");
String quote = quotes.getString("quote");
String author = quotes.getString("author");

答案 1 :(得分:1)

您可以只使用随机数生成器。

Random rand = new Random();
jsonArray.getJSONObject(rand.nextInt(jsonArray.length());

答案 2 :(得分:1)

当获得所有引号时,将JsonArray保存起来以备后用,并显示其中的随机引号。然后,当单击“下一步报价”时,调用相同的方法以显示先前下载的JsonArray中的随机报价。

JSONArray jsonArray;

@Override
public void onResponse(JSONObject response) {
    try {
        progress.hide();
        jsonArray = response.getJSONArray("quotes");
        displayRandomQuote();

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

显示随机报价的方法是:

public void displayRandomQuote(){
    // Get the total number of quotes
    int totalQuotes = jsonArray.length();

    // Pick a random between 0 and the total
    Random r = new Random();
    int random = r.nextInt(totalQuotes);

    try {
        JSONObject quoteData = jsonArray.getJSONObject(random);
        int id = quoteData.getInt("id");
        String quote = quoteData.getString("quote");
        String author = quoteData.getString("author");

        quoteTV.setText("“ " + String.valueOf(quote) + " ”");
        authorTV.setText("Author " + ": " + String.valueOf(author));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}