【问题标题】:Getting id from one json and finding name of that code in json从一个 json 获取 id 并在 json 中查找该代码的名称
【发布时间】:2022-01-13 10:30:25
【问题描述】:

我正在从 json 中解析数据,像这样。

private void dataClass() {

        Intent intent = getIntent();
        String Fdate = intent.getStringExtra("date");

        // creating a variable for storing our string.
        String url = "https://coindar.org/api/v2/events?access_token={token}&filter_date_start=" + Fdate;
        // creating a variable for request queue.
        RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
        // making a json object request to fetch data from API.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(JSONArray response) {
                // inside on response method extracting data
                // from response and passing it to array list
                // on below line we are making our progress
                // bar visibility to gone.
                loadingPB.setVisibility(View.GONE);
                try {
                    // extracting data from json.
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject jsonObject = response.getJSONObject(i);
                        String caption = jsonObject.getString("caption");
                        String source = jsonObject.getString("source");
                        String sourceReliable = jsonObject.getString("source_reliable");
                        String important = jsonObject.getString("important");
                        int coinID = jsonObject.getInt("coin_id");
                        String priceChange = jsonObject.getString("coin_price_changes");
                        int tagNumber = jsonObject.getInt("tags");

                        // adding all data to our array list.
                        calendarEventModalArrayList.add(new CalendarEventModal(caption, source, sourceReliable, important, coinID, priceChange, tagNumber));
                    }

                    // notifying adapter on data change.
                    calendarEventRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {

                    // handling json exception.
                    e.printStackTrace();
                    Toast.makeText(CalendarEvent.this, "Something went amiss. Please try again later", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying error response when received any error.
                Toast.makeText(CalendarEvent.this, "Something wentaaaamiss. Please try again later", Toast.LENGTH_SHORT).show();
            }
        }) {
        };
        // calling a method to add our
        // json object request to our queue.
        queue.add(jsonArrayRequest);

    }

而json对象是这样的,

{
    "caption": "Landing Page Launch",
    "source": "https://coindar.org/en/event/bzx-protocol-bzrx-landing-page-launch-56269",
    "source_reliable": "true",
    "important": "false",
    "date_public": "2021-11-25 15:32",
    "date_start": "2021-12-08",
    "date_end": "",
    "coin_id": "8630",
    "coin_price_changes": "7.24",
    "tags": "15"
  },

我正在获取硬币 ID,现在从该硬币 ID,我想扫描另一个 json 文件,以获取该特定 ID,并从那里获取名称或符号,

另一个json包含,

{
    "id": "1",
    "name": "Bitcoin",
    "symbol": "BTC",
    "image_32": "https://coindar.org/images/coins/bitcoin/32x32.png",
    "image_64": "https://coindar.org/images/coins/bitcoin/64x64.png"
  },
  {
    "id": "2",
    "name": "Ethereum",
    "symbol": "ETH",
    "image_32": "https://coindar.org/images/coins/ethereum/32x32.png",
    "image_64": "https://coindar.org/images/coins/ethereum/64x64.png"
  },
    
  this continues for over 11,000 coins :(.

我的 bindviewholder 方法,

public void onBindViewHolder(@NonNull CalendarEventRVAdapter.CalendarEventViewHolder holder, int position) {
        // on below line we are setting data to our item of
        // recycler view and all its views.
        CalendarEventModal modal = calendarEventModal.get(position);
        holder.headingTV.setText(modal.getCaption());
        holder.priceChangeTV.setText(modal.getPriceChange() + "% from event announcement");

        if(modal.getSourceReliable().matches("true")) {
            holder.sourceReTV.setText("Source: Reliable");
        }

        if(modal.getSourceReliable().matches("false")) {
            holder.sourceReTV.setText("Source: Not-reliable");
        }
}

现在我的问题是,我如何在 bindviewholder 类上从第一个 json 获取硬币 ID,然后扫描第二个 json 以获取该 id 并获取硬币名称,然后执行holder.settext 的东西。

现在我正在解析第二个 json,如下所示,

private void dataClass2() {
        // creating a variable for storing our string.
        String url = "https://coindar.org/api/v2/coins?access_token={token}";
        // creating a variable for request queue.
        RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
        // making a json object request to fetch data from API.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(JSONArray response) {
                // inside on response method extracting data
                // from response and passing it to array list
                // on below line we are making our progress
                // bar visibility to gone.
                try {
                    // extracting data from json.
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject jsonObject = response.getJSONObject(i);
                        int cdID = jsonObject.getInt("id");
                        String cdnName = jsonObject.getString("symbol");
                        String cdsImage = jsonObject.getString("image_64");


                        // adding all data to our array list.
                        calendarCoinModalArrayList.add(new CalendarCoinModal(cdID, cdnName, cdsImage));
                    }

                    // notifying adapter on data change.
                } catch (JSONException e) {

                    // handling json exception.
                    e.printStackTrace();
                    Toast.makeText(Calendar.this, "Something went amiss. Please try again later", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying error response when received any error.
                Toast.makeText(Calendar.this, "Something wentaaaamiss. Please try again later", Toast.LENGTH_SHORT).show();
            }
        }) {
        };
        // calling a method to add our
        // json object request to our queue.
        queue.add(jsonArrayRequest);

    }

另外,在解析第二个 json 时

    private ArrayList<CalendarCoinModal> calendarCoinModalArrayList;
    private CalendarCoinRVAdapter calendarCoinRVAdapter;
}
calendarCoinModalArrayList = new ArrayList<>();

        // initializing our adapter class.
        calendarCoinRVAdapter = new CalendarCoinRVAdapter(calendarCoinModalArrayList, this);

        // calling get data method to get data from API.
        dataClass();

我们将不胜感激。

【问题讨论】:

  • 您是否在任何地方加载第二个 JSON 日期?
  • 如何加载并在任何地方公开可用,请指导。
  • 是在本地文件主机上还是在服务器上?有没有可以访问的路径?
  • 第一个 json 在 url(服务器)上。第二个 json 我放在我的 android studio 项目 res/raw/...
  • 好的。所以需要解析第二个JSON

标签: java json android-studio


【解决方案1】:

在使用settext 设置测试之前,您需要加载关于第二个JSON 内容的信息。试试这个从文件中读取 json 信息。

public String loadJSONFromResource() {
    String json = null;
    try {
        InputStream is = getActivity().getResources().openRawResource(R.raw.coindata);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

要基于id 属性进行搜索,假设您使用了ArrayList

CalendarCoinModal obj;
int searchId = somevalue;
for(CalendarCoinModal currObj : calendarCoinModalArrayList) {
    if(currObj.id == somevalue) {
        obj = currObj;
        break;
    }
}

【讨论】:

  • 好的,我解析了 uniquearraylist 中的第二个 json,现在我该如何搜索属性
  • obj 将是您的情况的预期结果。
  • 非常抱歉,打扰您了,但是您的(列表)回复实际上很有帮助,它会起作用的,我只是感到困惑,您能否说得更清楚,列表部分。跨度>
  • 如果您可以附上您的课程代码,我可以从中检查,否则我不知道您的课程包含哪些字段。您一定已经创建了一些模型类来代表第二类,对吧?我说的是这个。
  • 问题已更新,见最后部分。
猜你喜欢
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2020-03-30
  • 2019-09-14
  • 2013-06-14
  • 2015-11-14
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多