使用自定义类类型将json文件转换为Java映射

时间:2020-01-03 13:43:06

标签: java json dictionary

所以我目前正在尝试将json文件转换为Java映射。我只是使用下面的代码,按原样工作即可:

ObjectMapper mapper = new ObjectMapper();
try {
    Map<String, Object> map = mapper.readValue(new File(
        "res/cache.json"), new TypeReference<Map<String, Object>>() {
    });

} catch (Exception e) {
    e.printStackTrace();
}

但是,问题是我不希望地图的类型为Map<String, Object>,而是Map<String, NodeType>,在这里我创建了一个新的静态类,如下所示。

static class NodeType {
    // A map of all the nodes, for example '{0001 : node, 0002 : anotherNode}'
    public Map<String, Node> nodes; //Note: Node is another static class containing a map of values.

    public NodeType() {
        nodes = new HashMap<>();
    }
}

我的解决方案是将new TypeReference<Map<String, Object>>替换为new TypeReference<Map<String, NodeType>>,但是我目前遇到一个错误,即json和类的结构不完全匹配。为了进行解释,该类将每个变量作为json中的键/值,然后将映射作为另一个键/值映射。 有谁知道我如何“压平” NodeType类以使两个结构都匹配。

谢谢。

Json文件内容:

{
  "areas" : {
    "0001" : {
      "lightsOn" : false,
      "volume" : 30,
      "musicPlaying" : true,
      "videoPlaying" : false
    },
    "0002" : {
      "lightsOn" : false,
      "volume" : 15,
      "musicPlaying" : true,
      "videoPlaying" : false
    },
    "0003" : {
      "lightsOn" : true,
      "volume" : 60,
      "musicPlaying" : true,
      "videoPlaying" : false
    }
  },
  ...
}

添加一下,当我通过对象映射器解析NodeType类时,我得到了:

{
  "nodes" : {
    "0002" : {
      "states" : {
        "volume" : 15,
        "musicPlaying" : true,
        "lightsOn" : false,
        "videoPlaying" : false
      }
    },
    "0003" : {
      "states" : {
        "volume" : 60,
        "musicPlaying" : true,
        "lightsOn" : true,
        "videoPlaying" : false
      }
    },
    "0001" : {
      "states" : {
        "volume" : 30,
        "musicPlaying" : true,
        "lightsOn" : false,
        "videoPlaying" : false
      }
    }
  }
}

编辑:我觉得本教程可能是正确的-https://www.baeldung.com/jackson-map

1 个答案:

答案 0 :(得分:0)

要么创建与文件匹配的JSON表示形式,要么手动(反序列化)JSON。

JSON表示可能类似于

public class JSONContent {

    private Map<String, AreasContent> areas;
}

public class AreasContent  {

    private boolean lightsOn;
    private int volume;
    private boolean musicPlaying;
    private boolean videoPlaying;
}

用法:

JSONContent jsonContent = mapper.readValue(new File("res/cache.json"), JSONContent.class);

编辑:

关于您的评论,您可以尝试类似的

public class JSONContent {

    private Map<String, Map<String, Object>> areas;
}

用法如上所述。