【问题标题】:how to replace null JSON Array string value with empty string using retrofit 2? [duplicate]如何使用改造 2 将空 JSON 数组字符串值替换为空字符串? [复制]
【发布时间】:2021-08-12 12:41:30
【问题描述】:

我对 Android 开发比较陌生,遇到了一个问题。我通过标头传递 3 个参数,并在如下响应中使用 Retrofit2 从 JSON 获取一些值:

[
   {
    "SchemeCode": "202007.ABW.REG",
    "SchemeName": "202007.ABW.REG"
   }
]

如果没有响应,我会收到 null ([])。这是我的改造调用的 sn-p 以获取字符串值:

sLabel.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            View viewdialog = LayoutInflater.from(mContext).inflate(R.layout.neworder_item_dialog, null);
            TextView schemeName = viewdialog.findViewById(R.id.schemeName);
            Call<ArrayList<SchemeModel>> call = apiInterface.showSchemes(cardCode, itemCode, date);
            call.enqueue(new Callback<ArrayList<SchemeModel>>() {
                @Override
                public void onResponse(@NotNull Call<ArrayList<SchemeModel>> call, @NotNull Response<ArrayList<SchemeModel>> response) {
                    if (response.isSuccessful()){
                        mList = response.body();
                        if (mList != null) {
                            for (int pos = 0; pos < mList.size(); pos++) {
                                String scheme = mList.get(pos).getSchemeName();
                                schemeCode = mList.get(pos).getSchemeCode();
                                schemeName.setText(scheme);
                            }
                        } else {
                            schemeCd = schemeCode.replace(null, "");
                        }
                    }
                }
                @Override
                public void onFailure(@NotNull Call<ArrayList<SchemeModel>> call, @NotNull Throwable t) {
                    Toast.makeText(mContext, t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
         });

在这里,当我尝试用空字符串"" 替换String schemeCd 时,它只是不这样做,说ArrayList&lt;SchemeModel&gt; mList 永远不会为空。请帮我用空字符串替换 null schemeCd

【问题讨论】:

  • String.replace(,) 是一个字符串函数,它接受两个字符串参数。你不能把 null 放在那里。而且 null 不是字符串。
  • 嗨@Praveen 很好,但是如何将传入的nullschemeCode 替换为"" 空字符串并存储在新字符串中

标签: java android json arraylist retrofit2


【解决方案1】:

您收到的不是空数组 ("[]")。只需检查 "!mList.isEmpty()" 而不是 "mList != null"

【讨论】:

  • 嘿@Tausif 如果我根据你使用检查,我会收到Method invocation 'isEmpty' may produce 'NullPointerException' 警告。这并不能回答我的问题。我想用""空字符串替换schemeCode的传入null值并存储在新的String..
猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
相关资源
最近更新 更多