首页 > 解决方案 > Java 无法解析符号“地图”

问题描述

我正在尝试在 java 中使用 gson 和 guava 库来获取两个 JSON 文件之间的差异。

我收到错误消息:“无法解析符号'Maps'。我的 InteliJ 安装文件夹的 lib 文件夹中有番石榴库 jar 文件,pom.xml 文件中的依赖项如下所示:

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.0.1-jre</version>
        </dependency>

创建 diff 的函数如下所示

public static Map<String, Object> newCompare(JsonElement original, JsonElement output){
    Type type = new TypeToken<Map<String, Object>>(){}.getType();

    Map<String, Object> leftMap = gson.fromJson(original, type);
    Map<String, Object> rightMap = gson.fromJson(output, type);
    return Maps.Difference(leftMap, rightMap);
}

我尝试重新导入所有 maven 项目并寻找答案,但我找到的所有解决方案都是关于 android 地图的。你能给我一些关于如何解决这个问题的建议,或者提出任何其他的解决方案吗?十分感谢。

标签: javagsonguava

解决方案


首先,它是Maps::difference在 Google 的 Guava 中,而不是Maps::Difference(通常,我们从不使用PascalCase作为 Java 中的方法名称;而camelCase是最好的约定)。

其次,根据您的评论,我通过具有相同的依赖关系重现了您的问题:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

并导入

import com.google.common.collect.Maps;

之后,

Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();

Maps.difference(map1, map2);

工作得很好。


推荐阅读