【问题标题】:Error while deserializing JSON using Jackson : Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token使用 Jackson 反序列化 JSON 时出错:无法从 START_ARRAY 令牌中反序列化 java.util.LinkedHashMap 的实例
【发布时间】:2014-06-11 07:38:50
【问题描述】:

我正在尝试将 json 反序列化为 MyClass 对象,但每次我得到异常时,虽然我能够序列化 JSON 对象。

**com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token**

我试图反序列化的 json 是

 {
  "siteName": "avisports",
  "csAssetTypes": [
    "Content_C",
    [
      "name",
      "description",
      "subheadline",
      "abstract",
      "body",
      "headline",
      "subheadline",
      "avi_content_title",
      "avi_content_body",
      "avi_content_headline",
      "avi_content_abstract"
    ]
  ]
}

我的 Bean 有点像

public class GlContentServerConfig{

    private String siteName;
    private Map<String, List<String>> csAssetTypes = new HashMap<String, List<String>>();

    //getters ans setters
}

而我的服务方式是

@Override
    public GlContentServerConfig getConfiguredAttributes(String siteName, String assetType) throws Exception {
        if (this.configMap == null) {
            this.configMap = this.configDAO.getAllConfigs();
        }

        GlContentServerConfig config = new GlContentServerConfig();
        config.setSiteName(siteName);               

        config.setCsAssetTypes(csService.getAssetTypeAttributeList(assetType));

        GloballinkConfig obj = this.configMap.get(siteName);
        if (obj != null) {
            String jsonValue = obj.getGlConfigValue();

            config=this.mapper.readValue(jsonValue, GlContentServerConfig.class); // error comes from this line
            //List<GlContentServerConfig> glconfigList= this.mapper.readValue(jsonValue, new TypeReference<GlContentServerConfig>(){});
            //List<GlContentServerConfig> glconfigList = this.mapper.readValue(jsonValue, this.mapper.getTypeFactory().constructCollectionType(List.class, GlContentServerConfig.class));

            System.out.println("final : "+glconfigList.toString());

        }

        return config;
    }

我已经尝试了几乎所有的排列和组合。其中很少有人在代码中注释。 我无法弄清楚使用杰克逊的方法。请帮帮我。

【问题讨论】:

  • 但是您的POJO 不适合您的JSON。您必须创建两个新属性:String csAssetTypes 和 List&lt;String&gt; csAttributes,并从您的类中删除 Map&lt;String, List&lt;String&gt;&gt; csAssetTypes 属性。
  • JSON 在这种情况下是错误的。但是豆子必须是那样的。我想要一个用于迭代的键值对。所以我必须使用地图。

标签: java json jackson deserialization


【解决方案1】:

将@JsonProperty("csAssetTypes") 添加到您的 Bean 中:

public class GlContentServerConfig{

    private String siteName;
@JsonProperty("csAssetTypes") 
    private Map<String, List<String>> csAssetTypes = new HashMap<String, List<String>>();

    //getters ans setters
}

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 2016-06-05
    • 2014-06-23
    • 1970-01-01
    • 2020-06-16
    • 2015-01-04
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多