android - JsonArray 作为空字符串解析问题与改造

标签 android gson retrofit

我有一个 json,如果它有数据,其中 1 个键作为 jsonArray 出现,否则它作为空字符串出现。使用改造在 gson 中解析时出错。

  "section": "Technology",
  "subsection": "",
  "title": "Depiction of Amazon Stirs a Debate About Work Culture",
  "abstract": "Details of working conditions at Amazon led to a response from employees, relatives and friends.",
  "url": "http://www.nytimes.com/2015/08/19/technology/amazon-workplace-reactions-comments.html",
  "byline": "By THE NEW YORK TIMES",
  "item_type": "Article",
  "updated_date": "2015-08-18T07:35:33-5:00",
  "created_date": "2015-08-18T07:35:35-5:00",
  "published_date": "2015-08-19T04:00:00-5:00",
  "material_type_facet": "News",
  "kicker": "",
  "des_facet": [
    "Workplace Environment"
  ],
  "org_facet": [
    "Amazon.com Inc"
  ],
  "per_facet": "",
  "geo_facet": "",

des_facet、org_facet、per_facet、geo_facet 是 jsonArray,但您可以看到其中 2 个没有数据,因此以空字符串形式出现。

如何使用改造 +gson 处理这种情况。

Json 格式无法在服务器端更改。

有什么办法可以在android中实现吗?

最佳答案

好的,所以有两个选项可以解决这个问题

选项 1:

JSON 以我为例

"des_facet": [
        "Workplace Environment"
    ],
    "org_facet": [
        "Amazon.com Inc"
    ],
    "per_facet": ["Akshay"],
    "geo_facet": ""

在您的模型类中将这些变量转换为 Object 类型

@Expose
    @SerializedName("geo_facet")
    private Object geo_facet;
    @Expose
    @SerializedName("per_facet")
    private Object per_facet;

然后在你想设置数据的地方做如下操作

if (model != null)
        {
            if (model.getGeo_facet() != null || model.getGeo_facet() != "")
            {
                Object arr = model.getGeo_facet();
            }
            if (model.getPer_facet() !=null || model.getPer_facet()!= "")
            {
                Object arr = model.getPer_facet();
                if (arr!=null && arr.toString().length()>0)
                {
                    arr = arr.toString();
                    Log.d("akshay","arr= "+arr);
                    //Do your Stuff or Set data
                }
            }
        }

This is the output= 08-11 16:51:29.830 17951-17951/com.android.example D/akshay: arr= [Akshay]

选项 2:

Follow this这有点复杂

选项 3:

编写自己的自定义解析 like this并相应地处理您的回复

关于android - JsonArray 作为空字符串解析问题与改造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51798666/

相关文章:

javascript - JS : Bug converting string to Date

junit - Kotlin:gson 之后的单元测试断言对象

java - 如何将 json 字符串解析为 ArrayList<NameValuePair>

java - 使用 GSON 将对象的 "list"(作为对象)解析为 JSON 中的整数对象( HashMap )

android - 如何使用改造获取嵌套的 json 数组对象?

android - 无法获取提供者 androidx.lifecycle.ProcessLifecycleOwnerInitializer

Android:位图中的 RGB 值错误

android - 当相机以其为中心时,Box2D 主体滞后/跳跃

android - MockWebServer 和 Retrofit with Callback

android studio如何使用库模块中已经添加的库依赖项