所以这是我在intellij中遇到的一个非常非常奇怪的错误,如果我实例化一个JsonArray(在gson库中),它只有一个需要JsonElement作为参数的.add方法。
JsonArray foo = new JsonArray();
for (String bar : this.baz) {
foo.add(bar); // .add throws this error: java: incompatible types: java.lang.String cannot be converted to com.google.gson.JsonElement
}
顺便说一句,这是一个使用以下 gson 依赖项的 Maven 存储库:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
最佳答案
如果 add()
需要 JsonElement
则使用:
foo.add(new JsonPrimitive(bar))
Gson 2.8.2 提供了接收简单字符串的 add()
重载版本。
关于Java Gson .add 函数不采用 String 参数(maven 项目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093957/