为什么由于LinkedHashMap启动中的某些问题而收到Jackson ObjectMapper解析错误?

时间:2018-09-09 04:33:21

标签: json jackson

我想使用ObjectMapper读取此JSON:

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

我像这样使用Jackson Jackson:

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 个答案:

答案 0 :(得分:1)

provider json结构与模型映射结构不匹配。您有两种选择,要么在Map中更改,要么在json中更改。

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

如果更改json结构,如下所示。

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

  }

我认为最好更改Map内容,而不要更改JSON结构。