对于不同类型的值,JSON到POJO转换错误

时间:2015-06-18 11:25:38

标签: java json gson jsonschema2pojo

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

  

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预计BEGIN_ARRAY但是STRING   在第1栏第119栏

我的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;
    }

如果结果中没有代码段类型,我的代码工作正常。 试图用类型转换,这也没有帮助我。

处理此类情况的最佳方法是什么?

1 个答案:

答案 0 :(得分: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);