0

使用 Gson 将 JSON 数据转换为 POJO 时出现此错误。

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期 BEGIN_ARRAY 但在第 1 行第 119 列是 STRING

我的 JSON 是:

{  
   "success":true,      
   "result":[  
      {  
         "htmlId":"edit_text_1",
         "value":"3",
         "contentType":"Snippet"
      },
      {  
         "htmlId":"edit_text_2",
         "value":[  
            {  
               "type":"HTML",
               "value":"<ul>\n<li>This is a text from the static editable content.</li>\n</ul>"
            },
            {  
               "type":"Text",
               "value":"- This is a text from the static editable content."
            }             ],
         "contentType":"Text"
      }
   ]
}

对于每个结果,值类型可能不同。有时它是一个字符串值或一个数组。

这是我的结果:

    private String htmlId;  
    private Object value = new ArrayList<Object>();
    private String contentType;

    public String getHtmlId() {
        return htmlId;
    }
    public void setHtmlId(String htmlId) {
        this.htmlId = htmlId;
    }
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        if(value instanceof String)
        this.value = (List<String>)value;
    else if(value instanceof ArrayList)
        this.value = (ArrayList<MarketoTypeValue>)value;
    }

    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

当结果中没有片段类型时,我的代码可以正常工作。尝试使用类型转换,这也对我没有帮助。

处理这种情况的最佳方法是什么?

4

1 回答 1

1

首先定义一个值类

class Value {
    private String type;
    private String value;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

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

然后更新你的大根 pojo

class Pojo {
    private String htmlId;
    private Collection<Value> valuea;
    private String contentType;

    public String getHtmlId() {
        return htmlId;
    }

    public void setHtmlId(String htmlId) {
        this.htmlId = htmlId;
    }

    public Collection<Value> getValuea() {
        return valuea;
    }

    public void setValuea(Collection<Value> valuea) {
        this.valuea = valuea;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
}

并使用 Gson 进行转换

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    final Collection<Pojo> collection = gson.fromJson(json, Collection.class);
于 2015-06-18T12:46:48.093 回答