java - 生成具有列表和字符串类型属性的 JSON 模型

标签 java android json gson

预先感谢那些能够看到我的出版物的人。我正在使用服务,并且有以下 JSON

"custom_attributes": [                  
        {
            "attribute_code": "meta_description",
            "value": "Calzado"
        },
        {
            "attribute_code": "category_ids",
            "value": [
                "2",
                "151",
                "161",
                "163"
            ]
        }
    ]

如果我将 Value 属性放入列表中,我尝试的操作会出现以下错误。

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 8375 path $.custom_attributes[0].value

型号

public class CustomAttribute {

@SerializedName("attribute_code")
private String attributeCode;
@SerializedName("value")
private List<String> value = null;

public String getAttributeCode() {
return attributeCode;
}

public void setAttributeCode(String attributeCode) {
this.attributeCode = attributeCode;
}

public List<String> getValue() {
return value;
}

public void setValue(List<String> value) {
this.value = value;
}

}

最佳答案

"custom_attributes"本身是一个包含对象的数组

我假设你在某个地方有 List<CustomAttibute>

并且该数组内部没有一致的对象格式。 value既是一个字符串,又是一个 List<String>

你能做的最好的就是 private Object value = null; ,那么您必须检查其类型并稍后在运行时进行转换,否则您不能将 Retrofit 与 Gson 转换器一起使用,因为 Gson 期望列表中形成一致的对象类型(意味着对于每个 JSON 键,只有一种值类型)。

关于java - 生成具有列表和字符串类型属性的 JSON 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53234206/

相关文章:

json - 有微博份额计数终点吗

java - 在类方法中递归地反转链表

java - jboss-序列化记录器级别不清楚

c# - 不想 JSON 序列化整个类列表

python - 如何将带有日期的文本写入 JSON 文件而不对其进行序列化

android - 有没有办法改变 Material 设计 CardView 特定角的半径

Java String split ("|") 方法调用无法正常工作

java - Android 小通知图标在 5.1 中不显示(LOLLIPOP)

Android Recycler view OnItemTouch work only click on text view

android - 带有自签名 SSL 证书问题的 HTTPS... 解决方案还是更好的方法?