首页 > 解决方案 > 使用 Jackson 如何在 JSON 包含对象列表时将其映射到对象

问题描述

这是我的 JSON 有效负载

{
  "allEnvs": ["qa", "dev", "prestaging"],
  "env": "qa",
  "envUrls": [{
    "qa": {
      "cutomeUrl": "testUrl",
      "adminUrl": "",
      "webUrl": "https://test.try.val",
      "salesUrl": ""
    },
      "dev": {
      "cutomeUrl": "testUrl",
      "webUrl": "",
      "salesUrl": ""
    },
    "prestaging": {
      "cutomeUrl": "testUrl",
      "webUrl": "",
      "salesUrl": ""
    }
  }],
  "isCommonUsers": "true",
  "commonUsers":[ {
    "teacher": {
      "fName": "test",
      "lName": "test"
    },
    "student": {
      "fName": "test",
      "lName": "test"
    },
    "ta": {
      "fName": "test",
      "lName": "test"
    }
  }],
  "commonCodes": ["test1", "test2", "test3"]
}

我想知道如何为我的“Conf.class”映射“envUrls”、“commonUsers”

ObjectMapper mapper = new ObjectMapper();
CommonConf cnf = mapper.readValue( new File("src/main/resources/configs/config.json"), Conf.class);

标签: javajsonjackson

解决方案


您可以Conf使用以下内容注释您的课程:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Conf {
   ...
}

它在解析 JSON 时忽略未知属性

文档:JsonIgnoreProperties


推荐阅读