代码之家  ›  专栏  ›  技术社区  ›  tanmayghosh2507

为什么由于LinkedHashMap启动中的一些问题而导致Jackson ObjectMapper解析错误?

  •  0
  • tanmayghosh2507  · 技术社区  · 6 年前

    我想使用ObjectMapper阅读此JSON:

    {
      "basePath": "/v1",
      "models": {
        "Course":{
          "number": "integer",
          "name": "string",
          "description": "string"
        },
        "Department": {
          "name": "string",
          "code": "string"
        }
      }
    }
    

    ObjectMapper mapper = new ObjectMapper();
    InputStream inputStream = Input.class.getResourceAsStream("/input.json");
    Input input = mapper.readValue(inputStream, Input.class);
    

    其中输入为:

    public class Input {
    
      String basePath;
      Map<String, Map<String, Map<String, String>>> models;
    
      public String getBasePath() {
        return basePath;
      }
    
      public void setBasePath(String basePath) {
        this.basePath = basePath;
      }
    
      public Map<String, Map<String, Map<String, String>>> getModels() {
        return models;
      }
    
      public void setModels(Map<String, Map<String, Map<String, String>>> models) {
        this.models = models;
      }
    }
    

    但是我得到了JSON映射错误。

    Can not instantiate value of type [map type; class java.util.LinkedHashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] from JSON String; no single-String constructor/factory method
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gaurav Srivastav    6 年前

    provide json结构与models map结构不匹配。您有两个选择,要么在Map中更改,要么在json中更改。

    Map<String, Map<String, String>> models;
    

    如果json结构发生如下变化。

    {
      "basePath": "/v1",
      "models": {
        "Course":{
          "Details":{
          "number": "integer",
          "name": "string",
          "description": "string"
          }
          }
        }
    
      }
    

    我认为最好改变Map的内容,而不是改变JSON的结构。