java和json jackson属性 - 运行时的不同类型 [英] java and json jackson property - different types at run-time

查看:155
本文介绍了java和json jackson属性 - 运行时的不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用外部Web服务来获取json对象。该对象具有属性value,有时是String,有时是字符串数组。

I am calling an external web-service to get an object as json. This object has a property "value" which is sometimes a String and sometimes an array of Strings.

public class MyClass {

    // ... other variables

    private String value;

    public String getValue() {
        return value;
    }

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

目前,我收到错误 org.codehaus.jackson.map.JsonMappingException:无法从START_ARRAY令牌中反序列化java.lang.String的实例抱怨此字段。我想知道是否有人可以给我一个提示,在我的班级中定义的正确方法。

Currently, I get an error org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token complaining about this field. I was wondering if some one could give me a hint on what is the correct way of defining value in my class.

这是我必须处理的样本json的一部分:

This is a part of a sample json that I have to deal with:

    {
      "id": 12016907001,
      "type": "Create",
      "value": "normal",
      "field_name": "priority"
    },
    {
      "id": 12016907011,
      "type": "Create",
      "value": [
        "sample",
        "another"
      ],
      "field_name": "tags"
    }

谢谢。

- 编辑

我将值的类型更改为Object并解决了我的问题问题。但是,我仍然想知道是否有更好的方法来处理这种情况。

I changed the type of the value to Object and it solved my problem. However, I am still wondering if there is a better way to handle this case.

推荐答案

一个简单的黑客就是启用< a href =http://fasterxml.github.com/jackson-databind/javadoc/2.1.1/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_SINGLE_VALUE_AS_ARRAY =noreferrer> DeserializationFeature#ACCEPT_SINGLE_VALUE_AS_ARRAY 然后使用Daniel的答案。如果Web服务返回一个字符串,Jackson会将其转换为单元素集合。

A simple hack would be to enable DeserializationFeature#ACCEPT_SINGLE_VALUE_AS_ARRAY and then use Daniel's answer. If the web service returns a string, Jackson will turn it into a single-element collection.

编辑:

如果您无法升级到Jackson 1.8或更高版本以使用此功能,您可以执行以下操作:

If you can't upgrade to Jackson 1.8 or higher to use this feature, you could do something like:

private Collection<String> value;

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

public void setValue(Object value) {
    if (value instanceof Collection) {
        this.value = (Collection<String>) value;
    } else {
        this.value = Arrays.asList((String) value);
    }
}

这篇关于java和json jackson属性 - 运行时的不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆