【问题标题】:Read List from JSON file从 JSON 文件中读取列表
【发布时间】:2020-09-01 06:19:00
【问题描述】:

我一直在尝试实现一种从 JSON 文件中读取嵌套 ArraList 的方法,但没有成功。

我的 JSON 文件具有以下结构:

 {
  "INT": {
    "Company": "mock company",
    "id": "0123456789X",
    "IntegerForm" : [1, 5, 7, 10],
    "StringForm": ["string 1", "string 2", "string 3"],
    "NestedMap" : {
        "key1" : "value1",
        "key2" : "value2"
    }
  },
  "TEST": {
    "Company": "mock company",
    "id": "0123456789X",
    "IntegerForm" : [1, 5, 7, 10],
    "StringForm": ["string 1", "string 2", "string 3"],
    "NestedMap" : {
        "key1" : "value1",
        "key2" : "value2"
    }  },
  "PRE": {
    "Company": "mock company",
    "id": "0123456789X",
    "IntegerForm" : [1, 5, 7, 10],
    "StringForm": ["string 1", "string 2", "string 3"],
    "NestedMap" : {
        "key1" : "value1",
        "key2" : "value2"
    }    
  }
}

我有几个级别的嵌套地图,我可以使用以下类读取它们:

public class JSONMapper {
    private HashMap<?, ?> jsonMap;

    public JSONMapper(String jsonPath) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        jsonMap = objectMapper.readValue(new File(jsonPath), HashMap.class);
    }

    public HashMap<?, ?> getJsonMap(String key) {
        return (HashMap<?,?>)jsonMap.get(key);
    }
}

要读取嵌套地图,我只需将它们转换如下:

HashMap<?, ?> dataMap;
JSONMapper mapper;
mapper = new JSONMapper("src/test/resources/datatest/example.json");
dataMap = mapper.getJsonMap("TEST");
HashMap <String, HashMap<String, String>> = (HashMap <String, HashMap<String, String>>) dataMap.get("NestedMap")

如何实现类似的方法来分别读取 IntegerForm 和 StringForm 作为 List 和 List 的值? 我想做类似的事情

new ArrayList ((List<Integer>) mapper.getJSONArray("IntegerForm"))

【问题讨论】:

    标签: json list dictionary arraylist jackson


    【解决方案1】:

    在尝试了多个已发布的解决方案数小时后,我意识到我正在访问一个映射键(来自属性文件),该键不存在于 json 文件中......这就是为什么我尝试的所有解决方案都不起作用的原因。

    这是我的最后一课,如果有人感兴趣,它可以从 JSON 文件中读取通用地图:

    public class JSONMapper {
        private HashMap<String, Object> jsonMap;
    
        public JSONMapper(String jsonPath) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            jsonMap = objectMapper.readValue(new File(jsonPath),
                new TypeReference<HashMap<String,Object>>(){});
        }
    
        @SuppressWarnings("unchecked")
        public HashMap<String, Object> getJsonMap(String key) {
            return (HashMap<String, Object>)jsonMap.get(key);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多