Json Mapping Exception无法将实例反序列化为START_ARRAY标记

Mar*_*bel 14 java json cxf jax-rs jackson

我正在尝试将我的json请求解析为我的模型.我不知道这段代码有什么问题.json的语法在Java模型上看起来也是正确的和注释.我不知道为什么我会收到如下错误:

Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of ParametersType out of START_ARRAY token
(through reference chain: Document["parameters"])
Run Code Online (Sandbox Code Playgroud)

Java模型:

@JsonIgnoreProperties( ignoreUnknown = true )
public class Document {

   @XmlElement( required = true )
   @JsonProperty( "templateId" )
   protected String templateId;

   @JsonProperty( "parameters" )
   @XmlElement( required = true )
   protected ParametersType parameters;

   @JsonProperty( "documentFormat" )
   @XmlElement( required = true )
   protected DocumentFormatType documentFormat;

...}

@JsonIgnoreProperties( ignoreUnknown = true )
public class ParametersType {

    @JsonProperty( "parameter" )
    protected List<ParameterType> parameter;

...}

@JsonIgnoreProperties( ignoreUnknown = true )
public class ParameterType {

    @XmlElement( required = true )
    @JsonProperty( "key" )
    protected String key;

    @XmlElement( required = true )
    @JsonProperty( "value" )
    @XmlSchemaType( name = "anySimpleType" )
    protected Object value;

    @JsonProperty( "type" )
    @XmlElement( required = true, defaultValue = "STRING_TYPE" )
    protected ParamType type;

....}
Run Code Online (Sandbox Code Playgroud)

Json代码:

{
    "templateId": "123",
    "parameters": [
        {
            "parameter": [
                {
                    "key": "id",
                    "value": "1",
                    "type": "STRING_TYPE"
                },
                {
                    "key": "id2",
                    "value": "12",
                    "type": "STRING_TYPE"
                }
            ]
        }
    ],
    "documentFormat": "PDF"
}
Run Code Online (Sandbox Code Playgroud)

gre*_*ker 20

您已声明parameters为单个对象,但您将其作为JSON文档中的多个对象的数组返回.

您的模型当前将参数节点定义为ParametersType对象:

@JsonProperty( "parameters" )
@XmlElement( required = true )
protected ParametersType parameters;
Run Code Online (Sandbox Code Playgroud)

这意味着您的模型对象需要一个类似于以下内容的JSON文档:

{
    "templateId": "123",
    "parameters": {
            "parameter": [
                {
                    "key": "id",
                    "value": "1",
                    "type": "STRING_TYPE"
                },
                {
                    "key": "id2",
                    "value": "12",
                    "type": "STRING_TYPE"
                }
            ]
        },
    "documentFormat": "PDF"
}
Run Code Online (Sandbox Code Playgroud)

但是在您的JSON文档中,您将返回一个ParametersType对象数组.因此,您需要将模型更改为ParametersType对象列表:

@JsonProperty( "parameters" )
@XmlElement( required = true )
protected List<ParametersType> parameters;
Run Code Online (Sandbox Code Playgroud)

您返回一个ParametersType对象数组的事实是解析器抱怨无法从START_ARRAY反序列化对象的原因.它正在寻找具有单个对象的节点,但在JSON中找到了一个对象数组.