我有一个 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/