如何使用改造 2 将空 JSON 数组字符串值替换为空字符串? [复制]

Posted

技术标签:

【中文标题】如何使用改造 2 将空 JSON 数组字符串值替换为空字符串? [复制]【英文标题】:how to replace null JSON Array string value with empty string using retrofit 2? [duplicate] 【发布时间】: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 替换为"" 空字符串并存储在新字符串中 【参考方案1】:

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

【讨论】:

嘿@Tausif 如果我根据你使用检查,我会收到Method invocation 'isEmpty' may produce 'NullPointerException' 警告。这并不能回答我的问题。我想用""空字符串替换schemeCode的传入null值并存储在新的String..

以上是关于如何使用改造 2 将空 JSON 数组字符串值替换为空字符串? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在不将空值发送到输出数组的情况下拆分字符串

如何解析具有相同键的不同数据类型的改造对象的json数组

如何将空 JSON 数据推送到 Observable<any[]> angular 2 类型的数组字段

如何将空输入值更改为空数组?

将空 JSON 数组反序列化为空 TreeMap

如何将空的 DateTime 值传递给 json?